Integer Class possible NullPointerException

While I was debugging, I got NPE which is not happy. When I glanced at the codes, it seemed that there was no problem. But after looking through line by line, I finally got the point.

For example, let's have a class Result.

public class Result {
    private Integer rcode;
    public Integer getRcode() {
        return rcode;    }

    public void setRcode(int rcode) {
        this.rcode = rcode;    }

}

It has only one Integer variable. If the class is instanciated from json or without validation, rcode could not be initialized and could not have any value. 

And at the point the value is compared, NPE comes.

Result result = new Result();
if(result.getRcode()==1000){  // NPE happens!    System.out.println("this cannot be reached.");}

Same situation can happen if we take this variable as a method with primitive parameter.

public static void printReturnCode(int rcode){
    System.out.println("this also cannot be reached.");
}

public static void hateNPE(){
    printReturnCode(result.getRcode()); // NPE happens!
}

I hope this could be caught automatically in IDE. Before than that, I should consider by myself.

Comments

Popular posts from this blog

삼성전자 무선사업부 퇴사 후기

개발자 커리어로 해외 취업, 독일 이직 프로세스

코드리뷰에 대하여