IT/Programming / / 2023. 4. 27. 09:47

<Effective Java> RULE 14 public 클래스 안에는 public 필드를 두지 말고 접근자 메서드를 사용하라

반응형

 

필드에 직접 조작할 수 있기 때문에 캡슐화 이점을 누릴 수 없다(규칙 13)

class Point{
    public double x;
    public double y;
}
//아무런 기능도 없는 쓰레기 클래스 생성
 

선언된 패키지 밖에서도 사용 가능한 클래스에는 접근자 메서드를 제공하라(규칙 14)

class Point{
    private double x;
    private double y;
    
    public Point(double x, double y){
        this.x = x;
        this.y = y;
    }
    
    public double getX() {return x;}
    public double getY() {return y;}
    
    public void setX(double x) {this.x =x;}
    public void setY(double y) {this.y = y;}
}
 

 public 클래스의 데이터 필드를 공개하면 그 내부 표현을 변경 할 수 없게 된다.

 변경하면 이미 작성된 클라이언트 코드를 깨뜨리게 된다.

 클라이언트 코드가 클래스 내부안에 종속된다는 문제가 있지만 같은 패키지 않에 있을 수 밖에 없다는 점을 고려해야 한다.

내부 표현을 공개한 예(java.awk - Dimension Class)

 

→ The Dimension class encapsulates the width and height of a component (in integer precision) in a single object. The class is associated with certain properties of components. Several methods defined by the Component class and the LayoutManager interface return a Dimension object.

Normally the values of width and height are non-negative integers. The constructors that allow you to create a dimension do not prevent you from setting a negative value for these properties. If the value of width or height is negative, the behavior of some methods defined by other objects is undefined.

변경 불가능 필드를 외부로 공개하는 public 클래스

 

→ 모든 객체가 올바른 시간을 나타내도록 보장

public final class Time{
    private static final int HOURS_PER_DAY =24;
    private static final int MINUTES_PER_HOUR =60;
    
    _public final int hour;_
    _public final int minute;_
    
    public time(int hour, int minute){
        if(hour < 0 || hour >= HOURS_PER_DAY)
            throw new IllegalArgumentException("Hour : " + hour);        
        if(minute~)
        
        this.hour = hour;
        this.minute = minute;
    }
}
 

 public 클래스는 변경 가능 필드를 외부로 공개하면 안 된다.

 변경 불가능 필드(final)인 경우에는 외부로 공개하더라도 많은 위험은 없지만 그럴 필요가 있는지 의문이다

 

 

반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유