Fix all your null errors

Are you annoyed from all of this null error that always break your code? And what if I tell you that there is a solution to fix that problem?

If you are interested let me explain you what is a Null Object.

The Null Object Pattern

As its name shows it is a Design Pattern that is here to get rid of a certain problem easily.

This solution instead using null where there is no result propose to return an object with default values.

For example if I try to fetch the author from a post on a blog, it will return me an object Author with a name set to Unknown instead of null.

The advantages of the Null Object Pattern

The main advantage from this approach is that where the null value gonna break your logic by not implementing methods or properties from the class, the null object is an instance from the class that behave exactly the same way as any other instance without any side effect.

This is a huge boost in your code as you don’t need anymore to test if the instance exist at the risk to forget it and create a fatal error in your code breaking it.

The second main advantage from this approach is for testing. As we already have a default object that is returned this can be a stub when we are testing. This providing us an object already created when we will have to take care of that part.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *