Take this constructed example:
def fetch_person(person_id, country_code=None):
if is_fully_qualified(person_id):
return person_source_1.fetch_person(person_id)
else:
return person_source_2.fetch_person(person_id, country_code)
If the function caller supplies the right kind of person_id
the country_code
is not necessary. Should I be guarding against the use in that case, like this:
def fetch_person(person_id, country_code=None):
if is_fully_qualified(person_id):
if country_code:
raise Exception("The country_code argument is not nessary if person_id is fully qualified.")
return person_source_1.fetch_person(person_id)
else:
return person_source_2.fetch_person(person_id, country_code)
I feel the user might be confused about the business logic if they supply the country code.
There seems to be some confusions about the question, maybe because of the nature of the example. Here is a simpler example:
def area(shape, x, y=None):
if shape == 'square':
return x ** 2
elif shape == 'rectangle':
return x * y
elif shape == 'circle':
return 3.14 * (x ** 2)
else:
raise ShapeNotSupportedException()
I can imagine three possible exceptions here. An exception in the square
branch if y
is given at all. An exception in the square
branch if x != y
. An exception in the circle
branch if y
is given at all, because circles don't have a second dimension to be defined.
Here is the one for just refusing y:
def area(shape, x, y=None):
if shape == 'square':
if y is not None:
raise InvalidArgument()
return x ** 2
elif shape == 'rectangle':
return x * y
elif shape == 'circle':
if y is not None:
raise InvalidArgument()
return 3.14 * (x ** 2)
else:
raise ShapeNotSupportedException()
Here is one where we are more lenient for squares, and only check if the argument makes sense or not:
def area(shape, x, y=None):
if shape == 'square':
if y is not None:
if y != x:
raise InvalidArgument()
return x ** 2
elif shape == 'rectangle':
return x * y
elif shape == 'circle':
if y is not None:
raise InvalidArgument()
return 3.14 * (x ** 2)
else:
raise ShapeNotSupportedException()
The alternative is of course just to ignore y
if it isn't needed.
fetch_person_qualified(person_id)
andfetch_person_unqualified(person_id, country_code)
?person_id
is qualified or not (which in turn means they would be better off calling a specific method for fetching a qualified/unqualified person) or they don't, and they'll eventually run into an exception because they providedcountry_id
when they shouldn't have, or vice-versa. Which in turn just forces them to wrap the call in atry/except
block, one layer above from your function.