We usually put unnecessary checks in our business logic to avoid failures.
Eg.
1. public ObjectABC funcABC(){
ObjectABC obj = new ObjectABC;
..........
..........
//its never set to null here.
..........
return obj;
}
ObjectABC o = funABC();
if(o!=null){
//do something
}
Why do we need this null check if we are sure that it will never be null? Is it a good practice or not?
2. int pplReached = funA(..,..,..);
int totalPpl = funB(..,..,..);
funA() just puts a few more restriction over result of funB().
Double percentage = (totalPpl==0||totalPpl<pplReached) ? 0.0 : pplReached/totalPpl;
Do we need 'totalPpl<pplReached'
check?
The questions is: Aren't we swallowing some fundamental issue by putting such checks? Issues which should be shown ideally, are avoided by putting these checks.
What is the recommended way?
Think about your audience. A check is worthwhile when it
If your null
check above does not fall into these, or there is a simpler mechanism which would do the same, then leave it out.
Simpler mechanisms often include,
assert
s that cause code to fail early, and communicate intent without requiring you to put in error handling code that should never be reached and without confusing code coverage toolsIn this case, I would suggest adding an annotation
public @Nonnull ObjectABC funcABC(){
integrating findbugs into your build process, and maybe replacing
if(o!=null){
//do something
}
with
assert o != null: "funcABC() should have allocated a new instance or failed."
Aren't we swallowing some fundamental issue by putting such checks?
As a rule of thumb,
assert
s are good for double-checking your assumptions. If you can't sprinkle asserts into your code and quickly tell which are being violated then your fundamental problem is that you don't have a quick way to run your code against representative data to shake out problems.Finally, design by contract is a programming methodology that many have found useful for business logic code. Even if you can't convince your team to adopt the specific tools and practices, reading up on DbC might still help you reason and explain how to enforce the important invariants in your codebase.