Shall same datatypes be used to return from functions, or assign default values ? or None ? What is a better coding practice, and why ?
eg. Some pseudo codes in python :
/1
def my_position(): # returns a positive integer if found
if(object is present):
position = get_position()
return position # eg 2,3,4,6
else:
return None # or return -1 or 0 ??
/2
def get_database_rows():
do query to whatever database
if(rows are found):
return [list of rows]
else:
return None # or return empty list [] ?
/3
the_dictionary = {'a' : 'john','b':'mike','c': 'robert' } # values are names i.e. non empty string
my_new_var = the_dictionary.get('z', None) # or the_dictionary.get('z','') ?
Raise an
IndexErrorif the item is not found. This is what Python’slistdoes. (Or maybe return the index where the item should have lived when doing a binary search or similar operation.)Think about what your function does, logically: if it returns a list of all items in a DB that satisfy some criterion, and there are no such items, then it makes sense to return an empty list since that allows all the usual list operations (
len,in) to function without the need for an explicit check.However, if the absence of the required items indicates inconsistency, then raise an exception.
My previous remark applies especially to this case: it depends on what you’re going to do with the value you get. An ordinary
dictjust raises aKeyErrorwhen a key is not found. You’re replacing that exception with a value, so you should know which value makes sense in the context of your program. If no value does, then just let the exception fly.That said, returning
Noneis often a bad idea because it may obscure bugs.Noneis the default return value in Python, so a function returning it may indicate nothing more than its author’s forgetting areturnstatement: