Don't return null from Boolean functions

Link to this posting

Postby Ursego » 21 Feb 2013, 22:12

Boolean methods must always return true or false (but never null).

Nobody knows if the calling method (which must make a code branching decision) will check the returned result for null. In fact, usually there is no such check, especially when the Boolean method is directly placed inside an if construction (like if this.booleanMethod()...). So, there is a high probability that a null, returned by a Boolean method, will be treated as false: if the else section exists, and the method returned null, the program flow will silently go to that else section and execute the logic, supposed to be executed on false (which was not actually returned!). That can produce a hidden bug. So, what do we have to return if the method cannot answer the asked question? Nothing! The best way to treat technical failures is throwing an exception rather than returning null.

What should we do if exceptions don't exist in the programming language (like T-SQL)? First of all, to display an error message to prevent a hidden bug. But, in this case, our method still needs to return something. As well as in a situation when we don't have the information, required to make the decision (for example, the examined value in a DB table is null). So, what to return if we don't want to return null? Think defensively. Use the common sense trying to prevent the bad. If the method checks an eligibility, return a value, saying "the entity is not eligible for what you asked". For example, if the method customerIsEligibleForDiscount() failed to connect to the database, it should return false (to prevent the company from losing money), but the method passengerMustBeCheckedBySecurity() should return true (to prevent a terrorist from boarding a plane).

Another approach without using exceptions is reporting success/failure of the method using an additional output (by-reference) argument. The calling method will be forced to pass a variable, so the chances are small that the success/failure code, returned via that argument, will be forgotten to be analized.
User avatar
Site Admin
Posts: 124
Joined: 19 Feb 2013, 20:33

IF you want to ((lose weight) OR (have unbelievable (brain function AND mental clarity))) THEN click:

free counters

eXTReMe Tracker