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);

myProduct.SetUnitPrice(5,7);

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.

Advertisements
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:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

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

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s