vendredi 22 juillet 2016

Best Way to catch NullPointerException [duplicate]

This question already has an answer here:

I have an entity Person , util class and some service where I work with it .

public SomeServiceClass {

public void someFunction() throws EntityNotFoundException, PersonTerminatedException{
Person p = getPerson(); // no matter how to retrieve 
if(p==null){
throw new EntityNotFoundException();
}else if(SomeUtilClass.isTerminated(p)){
 throw new  PersonTerminatedException();
}// other logic below     

Util class looks like

public SomeUtilClass{
public static boolean isTerminated(Person p){
return p.getLc().intValue()==2;
}
}

The question is where 's better to check attribute lc of object p for null ?? In util class before call p.getLc() so code would be like

p.getLc()!=null && p.getLc().intValue()==2

or it's better to check it in service class

else if(p.getLc()!=null && SomeUtilClass.isTerminated(p))

Don't suggest to put p.getLc().intValue()==2 inside else if , because in util class here might be more difficult logic .

Aucun commentaire:

Enregistrer un commentaire