In general, I'm a big fan of applying the Samurai Principle (return successfully or don't return at all). Some things flow logically from this:
You never return null, and therefore never have to do null checks (Hooray!!!) You may decide to implement the Null Object pattern.
If your method cannot fulfill its contract (can't do what its name says), it should throw an exception. Forget that oft repeated mantra - exceptions are for exceptional situations. I personally heard Jeff Richter address that by saying, "that's the stupidest thing I ever heard."
Now, let's assume that we are using a repository type pattern in the data layer. This is basically a factory that returns an object or collection of objects based on querying a database. Standard procedure is to return a collection, populated by 1, many, or zero objects corresponding to the data found by a query. This is perfectly appropriate, and works well.
There is another case that is not so cut and dried - when you query the database by primary key expecting 1 and only 1 result. We have several options, but I'm not fully satisfied by any of them. Let's look at them.
1 - Treat it the same way as all the others, i.e. return a collection with 1 or zero objects.
This works, but just feels wrong.
2 - Follow the database model, i.e. return the object or null if not found.
I dislike this one.
3 - Use the Null Object pattern.
I like this one, but I have some reservations. Like, how do you keep the Null Object in sync with its counterpart?
4 - Apply the Samurai Principle, i.e. return the object or throw an exception if not found.
This appeals to the perfectionist in me.
5 - Find the object or create a new object, and return it.
I want to like this, but it seems to violate expectations.
Do you have any others or comments on these? Please post to comments.