Common Java Code Bugs


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

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)