Don’t return null

If you write a function returning an object instance you have to think about the special cases. This may be error cases or maybe situations where no object instance can be found or created. In such cases you will often see functions returning “null”.

For example you implement a product management object which shall offer a function to get the product by a product identifier. So you create the following function:

GetProduct(int productIdentifier)

But what do you want to do if there is no product with the given identifier? Or what to do if the product management component is not initialized yet? You may return “null” in these cases. But this may result in several issues. For example the following code will break in such a case.

Product myProduct = GetProduct(123);


In case “myProduct” is “null” the code will result in an error. Therefore returning null will create work in the calling code and it is a source for errors if the calling code missing the null checks.

A better way is to throw a specific error or return a special case object. Throwing an error allows standard error handling with try-catch blocks on the calling code or a subordinate error handling routine. Returning a special case object will allow to continue the use case. For example in the above case the function may return a new product with uninitialized parameters if the specific product is not found. Of course, such a special case object must match with the use cases and may also result in some issues.

In summary you should not return null. Instead you should throw a specific error. In defined use cases it may also be possible to return a special case object.

Dieser Beitrag wurde unter .NET, C#, Clean Code veröffentlicht. Setze ein Lesezeichen auf den Permalink.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

Du kommentierst mit deinem Abmelden /  Ändern )


Du kommentierst mit deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s