DEV Community

Discussion on: Unhealthy Code: Null Checks Everywhere!

Collapse
 
moopet profile image
Ben Sinclair

I don't particularly like the NullBoss pattern.

It means you have to introduce fictional objects to work around a problem, which moves the problem elsewhere. Now you can't make a currentLevel.hasBoss function without making checks for your special object, or adding a property to it called isActuallyARealBoss.

In that sort of instance, I'd use an array, since there could be multiple bosses. As for being able to assign an empty array, I'd make sure I was using a language that allowed me to do that, because I value my mental health!

I agree that functions shouldn't generally return "thing or null".

Collapse
 
sambenskin profile image
Sam Benskin • Edited

What would the hasBoss function be used for? My understanding is the null object pattern would handle it for you. If you want current level to do something, then just do it and let the Boss or NullBoss handle what to do in each situation

Collapse
 
olvnikon profile image
Vladimir

This way of handling nullable objects reminds me a special type in Functional programming called Option (or Maybe). It keeps two values: None and Some(val). While Some always keeps a real not null value and you can map it, None has nothing but it is not null.
I would also apply this pattern instead of creating null versions of objects because it is more generic and covers all nullable cases. For example, fp-ts provides such utilities as fromNullable.

Thread Thread
 
jamesmh profile image
James Hickey

Agree. This was a solution I debated whether to include in the book or not. Due to not wanting to take forever with the book, I decided to exclude it.

But I agree, there are many situations where using the option pattern works very well 👍

Collapse
 
jamesmh profile image
James Hickey

One of the benefits of this pattern is that you typically would avoid the need for a hasBoss method (unless there's an exceptional case where you would need that check). Otherwise, using null objects should remove the need to do that.

I would agree that an array of bosses would work well, if the scenario warrants it.

Thanks! Great feedback.