Maybe split lines 23-34 into a helper function? Looks like it would just need to take in params and raise an exception if necessary.