개념적으로 속성을 바꾸는 작업엔 setter를 써요

개념적으로 속성을 바꾸는 작업엔 setter를 써요

use_setters_to_change_properties 규칙에 대해 알아볼게요.

출처: Use a setter for operations that conceptually change a property.

본문

어떤 작업이 개념적으로 속성(property)의 값을 바꾸는 일이라면, 메서드로 감싸는 대신 setter를 쓰길 권해요.

BAD:

rectangle.setWidth(3);
button.setVisible(false);

GOOD:

rectangle.width = 3;
button.visible = false;

setWidth(3)처럼 동작(method)으로 부르기보다 rectangle.width = 3처럼 속성에 값을 할당하는 게 훨씬 자연스럽고, 코드를 읽는 사람에게도 “속성이 바뀌는구나” 하고 바로 와닿아요.

활성화

use_setters_to_change_properties 규칙을 켜려면 analysis_options.yaml 파일의 linter > rules 아래에 추가해요:

linter:
  rules:
    - use_setters_to_change_properties

YAML map 구문으로 lint 규칙을 설정하는 경우엔 linter > rules 아래에 use_setters_to_change_properties: true를 넣으면 돼요:

linter:
  rules:
    use_setters_to_change_properties: true

더 알아보기

  • Effective Dart에서 권장하는 이름 짓기 규칙이에요. 속성 변경이 아니라 계산이나 변환처럼 동작이 필요한 경우엔 메서드를 쓰는 게 맞아요.