开发者

Is an argument of zero a good option to allow user to say they want all results? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
开发者_如何学JAVA

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 9 years ago.

Improve this question

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 2 as 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 first n items.

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.


If the language supports overloading, then I would use an overload without the max parameter to indicate that all rows were requested. Alternatively, given nullable values and default values, I might use a single method with a nullable integer parameter with a default value of null.

In C#:

public IEnumerable<Record> GetRecords(int? maximumRecords = null);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜