Let's say you have a function that returns a date:
Date myFunc(paramA, paramB){
//conditionally return a date?
}
Is it appropriate to return null from this function? This seems ugly because it forces clients to check for null.
The "null object" pattern is an implementation pattern that addresses this concern.
I'm not a huge fan of the null object pattern, but yes, it makes sense to always return a list, even if is empty, rather than to return null.
However, say in Java, a null date would be one that is cleared and has the year 1970.
What is the best implementation pattern here?
The null object pattern is not for what you are trying to do. That pattern is about creating an object with no functionality in it's implementation that you can pass to a given function that requires an object not being null. An example is NullProgressMonitor in Eclipse, which is an empty implementation of IProgressMonitor.
If you return a "null" date, like 1970, your clients will still need to check if it's "null" by seeing if it's 1970. And if they don't, misbehaviour will happen. However, if you return null, their code will fail fast, and they'll know they should check for null. Also, 1970 could be a valid date.
You should document that your method may return null, and that's it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With