How often and where to make Null-Checks

cmlonder :

I'm trying to avoid overdo null checks, but at the same time I want to make null check whenever it needs to make the code robust. But sometimes I feel like it starts to be so much defensive since I don't implement API. Then I avoid some null-checks but when I start unit tests, it starts to always wait for runtime exceptions. What is the right approach, how to feel the balance. Here are the notes I have collected so far:

  • avoid unnecessary null-checks in private methods of the instance class since proper null checks are made before and instance class is responsible of this, not each function
  • make null checks in public methods and explain function behavior in the Contract for the public usage
  • make null checks in the constructor

Let me give an dummy example where my confusing starts:

Here is the default function of the interface:

default void someFunction() {

// instantiaded foo and filters
foo = processFoo(foo, filters);

// do some operations with foo
// null check if processFoo's contract returns null (description in the implementation)

}

Implementation:

Foo processFoo(foo, filters) {
// Should I null check foo and filters?

// Operations with foo.someFields
// Operations with filters.someFields

return foo; // If I null check then I should return some exception or null to the caller function. 
// If I don't null check just return received foo.
}
BigMike :

On a general rule, I never check for nulls when I'm in control of the calls, but if my code can be called by someone else, I do enforce checks, since you're talking about an API spec, you may check input parameters and throw IllegalArgumentException.

Of course, this it's not required, most of the times, when you have an NPE, there's an underlying bug somewhere, however if you are not in total control of calls, you will definitely need some extra effort. (expecially if your API will be called frequently, you need something to help you trace/identify bad calling patterns).

When designing an API, aside the architecture itself, you have to focus also on maintenance/troubleshooting and security, expecially if the API is publicly exposed (which means also sanitizing each and every parameter).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=116165&siteId=1