
For example, let’s say you want to write a helper or utility function to check if an employee object has medical claims. When should you return null from a method?Īlthough returning null is considered a bad practice, you may consider returning null if the sole purpose of your method is to show that there are no data and use it for display purposes rather than more functional tasks. Therefore, you need to define the error handling code with the method or let callers be aware of it and force them to handle that exception before it becomes a million-dollar mistake. All it takes is one missing null check to send an application spinning out of control.” “Don’t return NULL – When we return null, we are essentially creating work for ourselves and foisting problems for our callers. Martin, in his book “ The Clean Code“, a widely used handbook about better software craftsmanship, suggests avoiding returning null values.

In a system with different complicated integrations, such unhandled null references can have ripple effects, ultimately losing the collect functionality of the related features.Įven Robert C. For example, In C#, returning a null value leads to “NullReferenceException” in Java, this leads to NullPointerException, etc. The result is exceptions in the caller code if you haven’t explicitly handled it in your code.ĭifferent programming languages throw similar null exceptions.

Here is the thing: the method caller might not be aware that it returns a null.įor example, suppose you return a null object, and the method callers try to access the methods of the null object. He says, “ This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.” However, at a conference in 2009, Tony Hoare apologized for inventing it. The null reference was invented in 1965 by Tony Hoare when he was designing the “ first comprehensive type system for references in Object Oriented Language(OOP).” Since he found it easy to implement, he introduced the null reference. The null reference is often called the “worst mistake in software development”. Null reference – a billion-dollar mistake Thus, method callers could become victims of unhandled null values.īut if the method callers try to access the empty values, there will be no big issue as you do not need special handling. But developers may forget to write a null check. Returning null is okay if your code handles the returning null value. Especially when you return a collection, enumerable, or an object, you should avoid returning null.

It is best practice to return empty values rather than null ones. The GetData method returns null if no product is found in the database. The GetProduct method searches through the product database and returns the product object. Var product = _db.Products.GetData(k => k.ProductId = id)
