I would like to share with you some tips to deal/prevent NPE in your code:
The BIG IMPORTANT rule: do NOT assign / pass / return null value and keep your code as cohesive as possible.
Programming tips / techniques:
1. Return an empty collections instead of null.
For example:
List:
return Collections.emptyList()
Set:
return Collections.emptySet()
Map:
return Collections.emptyMap()
org.apache.commons.lang.ArrayUtils.EMPTY_XXX_ARRAY
2. Return
org.apache.commons.lang.StringUtils.EMPTY
or “” instead of null
3. Return “UNKNOWN” enum instead of null
4. Check null before executing a variable
5. Null-safe checking technique
if("Hello".equals(hello)) { }
instead of
if(hello != null) {
if(hello.equals("Hello")) { }
}
or
if(hello.equals("Hello")) { }
Principle and Pattern:
6. Null Object Pattern (https://sourcemaking.com/design_patterns/null_object/java-0)
(My favourite pattern belong with Template Method and Bridge)
Instead of
public Manager getManager(ManagerType inType){
switch(inType) {
case PROJECT:
return ProjectManager();
case DEPARTMENT:
return DepartmentManager();
default:
break;
}
return null;
}
Let try:
public Manager getManager(ManagerType inType){
switch(inType) {
case PROJECT:
return ProjectManager();
case DEPARTMENT:
return DepartmentManager();
default:
break;
}
return NullManager();
}
Design tips:
class NullManager extends Manager {
// Implement all abstract methods of Manager
// Override neccessary methods to drive to do "Nothing" or "Default" action.
}
7. Avoid too many dot syntax. (http://en.wikipedia.org/wiki/Law_of_Demeter)
For example:
getSettingManager().getSettingPanel().getHeaderPanel().getHeaderLabel().setText("Setting");
Class Variable:
8. Try initializing variable member of class before using it.
Direct initialization
private List mPersons = new ArrayList();
Initialize them in class Constructor
public Family() {
mPersons = new ArrayList();
}
Constructor dependency injection
public Family(List inPersons) {
mPersons = inPersons;
}
Provide accessibility through getter and using lazy initialization
public getPersons() {
if(mPersons == null) {
mPersons = new ArrayList();
}
return mPersons;
}
9. Avoid / eliminate method dependency injection (setter)
public setPersons(List inPersons) {
mPersons = inPersons;
}
NGUỒN: HTTP://EDWARDTHIENHOANG.WORDPRESS.COM/
EMAIL: EDWARDTHIENHOANG@GMAIL.COM
[/sourcecode]