One More Recipe Against NULL
You know what NULL is, right? It’s evil. In OOP, your method can return NULL, it can accept NULL as an argument, your object can encapsulate it as an attribute, or you can assign it to a variable. All four scenarios are bad for the maintainability of your code—there are no doubts about that. The question is what to do instead. Let’s discuss the “return it” part and I will suggest one more “best practice” on top of what
Look at this code:
What should this method do if the list is empty? Java’s Collections.max()
throws an exception. Ruby’s Enumerable.max()
returns nil
max()
returns FALSE
. Python’s max()
raises an exception. C#’s Enumerable.Max()
also throws an exception. JavaScript’s Math.max()
returns NaN
.Which is the right way, huh? An exception, NULL, false or NaN?
An exception, if you ask me.
But there is yet another approach, which is better than an exception. This one:
The “default” object will be returned if the list is empty. This feature is implemented in Python’s max()
function: it’s possible to pass both a list and a default element to return in case the list is empty. If the default element is not provided, the exception will be raised.
Say, you are designing a method findUserByName(), which has to find a user in the database. What would you return if nothing is found? #elegantobjects
--- Yegor Bugayenko (@yegor256) April 29, 2018