I have a function that will allow user to return a set of results. For the purpose of this discussion, assume it is returning a sequence of objects. I want to provide a facility for the caller to limit the number of objects returned.
In python:
def get_records(max=0):
# snipped ..
The max parameter will limit the number of records returned. If it is zero, I will return all. Is this good API design ?
As long as behaviour is documented, you can use any value you want, provided it’s outside the scope of what people would consider a “normal” parameter. By that I mean you would not use
2as the special value if clients of your code would ever want two things returned.So, provided there’s not a valid use case for returning zero things (a), then zero is as good a value as any to indicate “all items”.
(a) You may have a valid use case where there are side-effects in calling the function. An example is an arbitrary list where you call
getFirst(n)on it and that first sorts the list then returns the firstnitems.Clients may wish to call your code with
getFirst(0)to just sort the list without getting any values.Of course, I’d implement a totally separate function for that myself so this is a slightly contrived example but it hopefully illustrates the point I’m trying to get across.