May 02, 2005
What would you do: Conclusion
Many heartfelt thanks to Miki Watts, Phil Wilson, Benjamin Franciscoud, Doug Pardee, Aristotle Pagaltzis and Gerd Riesselmann who helped all helped out with my design question from last week. All your comments were very smart and insightful Now to the conclusion:
From the three options I mentioned, most commenters would choose to return a null value. Gerd said:
As a C++ programmer I tend to just return the null pointer NULL, which represents "no instance" - and that's what we have here. So it seems the natural thing to do.
Exceptions are too costly when they come in massive numbers and the Null Object is too funky an idea for the little good it provides. Miki writes about the Null Object:
Returning a Null object seems to be problematic, since then the callers have to check for the Null object that you provided, and not a generic null. If i were using that framework, it would certainly surprise me to get an object that was all empty, i would have thought that it's a bug.
Doug was the first to mention that the best solution might be something completely different:
A fourth possibility is to return an Array or a List of all of the Tags, rather than one at a time.
I'm all with Doug on that one. Moreover, if an object exposes a method that is bound to fail most of the time, it's probably a good idea to not offer this service in the first place. Aristotle argues further for returning a list:
What you really want is to offer the caller is a way to treat the "no such tag" case exactly the same as the "tag found" case, unless the caller is explicitly interested. By giving the caller a list of some form, this becomes possible: a list is a list is a list, whether it has 0 elements or 42.
So that's exactly what I did:
interface TagReader {
TagList getTags();
}
If you absolutely, positively must access a particular Tag, TagList offers a convenience method that's been renamed to searchTag with a checked NoSuchTagException to make clear that this is really a best-effort service:
interface TagList extends List<Tag> {
Tag searchTag(URI uri) throws NoSuchTagException;
}
Once again, thanks for your help!
P.S.: Benjamin posted a link to a fantastic interview with Josh Bloch about API design which is definitely worth your time.
Comments
Post a comment
Thanks for signing in, . Now you can comment. (sign out)
(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)