DEV Community

Discussion on: Unhealthy Code: Null Checks Everywhere!

Collapse
dontry profile image
Don

Hi James, how do you instantiate the NullBoss class? I reckon it still needs to do the null check in the first place, doesn't it?

Collapse
jamesmh profile image
James Hickey Author

The NullBoss doesn't do any null checking because it replaces the concept of null altogether.

const nullBoss = new NullBoss();
nullBoss.fight(player);
// Etc.

Usually with kind of pattern, you would have a factory of some kind create your objects for you.

Does that help?

Collapse
dimpiax profile image
Dmytro Pylypenko

Could you provide the practical example with NullBoss?
Cause the current example is not like dummy date, that can be used as mock. But the example which is far from reality, correct me if I wrong.

Thread Thread
olvnikon profile image
Vladimir

I think the whole idea of using NullObject is taken from Option type, which holds None or Some. When they is no null you don't think it exists. E.g. while Some holds a real not null value, which can be mapped, None always returns None. This approach is called "Railway programming".

fromNullable(null).map(double).map(tripple); // None
fromNullable(2).map(double).map(tripple); // Some(12)

null is avoided and the program doesn't crash. Just different way of thinking when there is no null.

Thread Thread
dimpiax profile image
Dmytro Pylypenko

As I know, the pattern was a long time before Optionals (some, none).
And what author proposes – it’s a big difference from it.
Using optionals you stop the execution flow, while the topic about redundant objects creation.

Thread Thread
lukejs profile image
Luke

2 examples I've seen in Minecraft:

Air blocks - they are blocks like any other, rather than nulls to represent a block not being present in a location

Also added in the last few versions (replacing null) - "Empty" item stacks - there is a singleton "ItemStack.EMPTY" and a method "ItemStack#isEmpty()"

Collapse
kopseng profile image
Carl-Erik Kopseng

Like in all OOP, you still need to make the decision on which class to create somewhere. What you gain by taking the decision at a higher-up place is the ability to avoid this decision in all other places.