왜 Getter & Setter 사용하는데

jiiiiiiiArchive.·2025년 1월 15일

🤯지식주머니🤯

목록 보기
67/98

그러게요 왜사용할까요 ?
이 질문에 답할 수가 없었다.
항상 이렇게 써야한다 ~ 이었고 프로젝트에서 Vo 패키지 내에 클래스들을 Getter & Setter로 만들었어서 그냥 정말 당연히 그렇게 코딩해야하는줄.

하지만 당연한게 어딨겠어.

그래서 알아본 Getter & Setter을 사용하는 이유.

Apple이라는 객체가 있다고 가정해보고, apple.color으로 프로퍼티로 바로 접근해 색 값을 가져와보겠다.

public class Apple {
    private String color;
    private int count;

    public Apple(String color, int count {
        this.color = color;
        this.count = count;
    }
}

위와 같이 접근하지 않고 getColor(), setColor() 메서드를 통해 경유해서 설정하도록 하는 기법이 Getter & Setter 개념이다.

public class Apple {
    private String color;
    private int count;

    public Apple(String color, int count) {
        this.color = color;
        this.count = count;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public static void main(String[] args) {
        Apple a1 = new Apple("red", 5);
        System.out.println(a1.getColor()); // red
    }
}

왜 사용하는데 그래서

  1. 캡슐화(Encapsulation)
    캡슐화가 뭔데 ?
    => 데이터(필드)와 이를 처리하는 메서드(기능)를 하나의 단위(객체)로 묶고 외부에서 직접 접근하지 못하도록 제한하는 것
    => 데이터를 보호하고 객체의 내부 구현을 숨기는 데 도움
  • 캡슐화 실현을 위해 private 접근제한자를 사용해 객체의 데이터(필드)를 외부로부터 보호
  • Getter와 Setter를 통해 필요한 경우에만 데이터에 접근하거나 수정할 수 있게
public class Animal {
	private String species;
    
    public String getSpecies() {
    	return species;
    }
    
    public void setSpecies() {
    	this.species = species;
    }
}
  1. 데이터 무결성 보장
  • 데이터를 수정하거나 읽는 과정에서 특정 조건 검증 가능 => 객체의 상태를 항상 유효한 값으로 유지할 수 있음
    public void setCount(int count) {
    	if(count > 0) {
       	this.count = count;
       } else {
       	throw new IllegalArgumentException("개수는 0개보다 많아야 합니다.");
       }
    }
  1. 변경에 유연한 설계
  • 필드에 직접 접근하면 내부 구현을 변경하지 어렵지만 Getter & Setter를 사용하면 내부 로직을 수정하더라도 외부 코드를 변경하지 않아도 된다.
    public void setSalary(double salary) {
    	this.salary = salary * 0.9; // 세금 공제 로직 추가
    }
  1. 디버깅과 유지보수 편리
  • Getter & Setter 메서드에 디버깅 코드나 로깅을 추가할 수 있어 문제 해결 및 유지보수에 유리
    public void setColor(String color) {
    	System.out.println("변경된 색상 : " + color);
       this.color = color;
     }
  1. 보안성 강화
  • 필드에 직접 접근을 막아 데이터가 의도치 않게 변경되는 것 방지

결국 객체지향 프로그래밍에서

1. 데이터를 안전하게 보호하고

2. 객체의 유연성과 유지보수성을 향상시키기 위해

3. 필요한 경우에만 사용하고

4. 과도하게 사용해 객체의 상태를 외부에서 쉽게 조작하지 않도록 주의하기 위해

사용한다는 것!

profile
이것저것 다 적는 기록장📚

0개의 댓글