When write code, I made so many simple mistakes, so I try to write them down here to remind me not to make same mistakes again.
Copy&Paste is evil.
Most times, the problem happens when I copy and paste, change it, but forget to change some places.
Take time to check and review code before start to compile or run tests. This can save me a lot of time.
Boolean condition
if(!valid) or if(valid).
if(a.equals(b)) or if(!a.equals(b))
if(map.isEmpty()) or if(!map.isEmpty())
Use &&, Not &
str != null & str.equalsIgnoreCase("true")
Throw NPE when str is null.
Forget else statement.
Think about what should be done in else statement.
Forget default in switch
NullPointerException
Use Optional to avoid NPE
Use NPE safe method
- like Objects.equals, CollecitonUtils.isEmpty, StringUtils.equals etc.
Forget to initialize variable, especially for instance variable.
Check Null, and handle the case.
NPE when unbox
int value = Long or (Long)obj;
the Long or obj may be null.
Float maxScore = null;
maxScore = docList.maxScore(); // if use float, here it may throws NullPonterException
check whether the collection is null before use for-loop or iterator.
for(String str: strList)
Forget to shutdown threadpool and wait for it finish
executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
Where to put executor.shutdown() or server.shutdown()
We have to wait until all tasks are done or submitted。
Add object more than one time
if (obj != null && (Long) obj == 0) {
sortedNL.add(label, queryValue);
queryValue = new NamedList<Object>();
}
sortedNL.add(label, queryValue == null ? new NamedList<Object>() : queryValue);
Forget to check for preconditions, null pointers - Defensive programming
Defensive programming teaches to check whenever you are in doubt excplicity about the method arguments.
When to call super.method()
Understand when we should call super.method and why.
In MyUpdateRequestHandler.init(NamedList),
If I call super.init(args), in createDefaultLoaders, the clientIdParamName would be null which is not expected.
Map Key
Once you put a key/value pair in a hash map you should not change the value of the key, ever, in any way that changes the hash code. If the key is changed where it generates a new hash code, you will not be able to locate the correct bucket in the HashMap that contains the key/value pair.
Throw exceptions to signal exceptional conditions instead of using Null flags
Memory Leak
- Non-static inner or anonymous class holds a reference to outer class.
- Lambda will create implicit reference only when we are using some method or field from the enclosing class.
- Use static inner class + WeakReference to rescue
Custom Map Key or Set object
- whether implements hashcode or equals correctly
TreeMap/TreeSet
- whether implement compareTo method correctly
Mutable key or object in Map or Set
References
Collected Java Practices
8 Common Code Violations in Java
Common Java Mistakes and Bug Patterns
Copy&Paste is evil.
Most times, the problem happens when I copy and paste, change it, but forget to change some places.
Take time to check and review code before start to compile or run tests. This can save me a lot of time.
Boolean condition
if(!valid) or if(valid).
if(a.equals(b)) or if(!a.equals(b))
if(map.isEmpty()) or if(!map.isEmpty())
Use &&, Not &
str != null & str.equalsIgnoreCase("true")
Throw NPE when str is null.
Forget else statement.
Think about what should be done in else statement.
Forget default in switch
NullPointerException
Use Optional to avoid NPE
Use NPE safe method
- like Objects.equals, CollecitonUtils.isEmpty, StringUtils.equals etc.
Forget to initialize variable, especially for instance variable.
Check Null, and handle the case.
NPE when unbox
int value = Long or (Long)obj;
the Long or obj may be null.
Float maxScore = null;
maxScore = docList.maxScore(); // if use float, here it may throws NullPonterException
check whether the collection is null before use for-loop or iterator.
for(String str: strList)
Forget to shutdown threadpool and wait for it finish
executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
Where to put executor.shutdown() or server.shutdown()
We have to wait until all tasks are done or submitted。
Add object more than one time
if (obj != null && (Long) obj == 0) {
sortedNL.add(label, queryValue);
queryValue = new NamedList<Object>();
}
sortedNL.add(label, queryValue == null ? new NamedList<Object>() : queryValue);
Forget to check for preconditions, null pointers - Defensive programming
Defensive programming teaches to check whenever you are in doubt excplicity about the method arguments.
When to call super.method()
Understand when we should call super.method and why.
In MyUpdateRequestHandler.init(NamedList),
public void init(NamedList args) { if (args != null) { SolrParams params = SolrParams.toSolrParams(args); Object obj = params.get(PARAM_CLIENTID_PARAM_NAME); if (obj != null) clientIdParamName = obj.toString(); } super.init(args); }In this case, I have to call super.init(args) at last, as init method in parent calls createDefaultLoaders, and in my subclasses, I overwrite createDefaultLoaders, which need parameter clientIdParamName.
If I call super.init(args), in createDefaultLoaders, the clientIdParamName would be null which is not expected.
Map Key
Once you put a key/value pair in a hash map you should not change the value of the key, ever, in any way that changes the hash code. If the key is changed where it generates a new hash code, you will not be able to locate the correct bucket in the HashMap that contains the key/value pair.
Throw exceptions to signal exceptional conditions instead of using Null flags
Memory Leak
- Non-static inner or anonymous class holds a reference to outer class.
- Lambda will create implicit reference only when we are using some method or field from the enclosing class.
- Use static inner class + WeakReference to rescue
Custom Map Key or Set object
- whether implements hashcode or equals correctly
TreeMap/TreeSet
- whether implement compareTo method correctly
Mutable key or object in Map or Set
References
Collected Java Practices
8 Common Code Violations in Java
Common Java Mistakes and Bug Patterns