Don't return null from Boolean functions


Link to this posting

Postby Ursego » 21 Feb 2013, 22:12

Boolean functions must always return true or false (but not null). Think defensively if the function is not able to return the asked value.

Nobody knows if the calling script (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 function is directly put inside an if construction (if this.BooleanFunction() then...). So, there is a high probability that a null, returned by a Boolean method, will be treated as false - it's acceptable in some cases, but not always. So, what do we have to return if the method cannot answer the asked question (for example, due to an error)? The best way to treat technical failures is throwing an exception rather than returning null!

But if your programming language doesn't support exceptions then simply 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 CustomerCanGetDiscount() failed to connect to the database, it should return false, but the method PassengerMustBeDoubleCheckedBySecurity() should return true in that situation.
User avatar
Ursego
Site Admin
 
Posts: 113
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