개발/JAVA

boolean 타입 명 앞의 is에 대해

보리ing 2021. 7. 11. 20:33

dto 객체에서 비어있는지 여부를 판단하기 위해 empty 라는 변수를 추가했다.

그리고 boolean형을 가져올때 isEmpty 식으로 boolean 타입을 묻곤 하기 때문에

큰 생각없이 변수 명을 isEmpty와 같이 지정하고 값을 가져올때도 isEmpty() 로 isEmpty 값을 가져 오도록 했다.

 

하지만 이처럼 is가 붙은 경우

isEmpty 값이 true를 주고 다시 isEmpty() 메서드를 통해 가져올 때

메서드의 내용은

    public boolean isEmpty() {
        return isEmpty;
    }

 

로 isEmpty의 값을 그대로 리턴하지만

isEmpty 의 값을 true로 줬기 때문에 false로 리턴한다.

 

boolean 형의 변수명의 규칙과 주의할 점을 찾아봐야 하겠다.

 

발견 1

Lombok @Getter는 primitiveType인 boolean 에는 is를 class인 Boolean에는 get prefix를 붙인다.

@Getter
public class BooleanGet {
    private boolean primitiveBoolean;
    private Boolean classBoolean;

    public BooleanGet(boolean primitiveBoolean, Boolean classBoolean) {
        this.primitiveBoolean = primitiveBoolean;
        this.classBoolean = classBoolean;
    }
}

 

    @DisplayName("type에 따라 get메서드가 다르다")
    @Test
    void getTest(){
        BooleanGet booleanGet = new BooleanGet(true,true);

        assertTrue(booleanGet.getClassBoolean());
        assertTrue(booleanGet.isPrimitiveBoolean());
    }

 

따라서 이와같은 특징에 따라, 개체인 경우 해당 필드명에 이미 is가 붙은 경우Boolean타입으로 선언하거나 직접 메서드를 작성하는 것과 같이 주의가 필요할 것 같다.