인스턴스를 만들 때는 static 메서드보다 생성자를 써요
인스턴스를 만들 때는 static 메서드보다 생성자를 써요
prefer_constructors_over_static_methods 린트 규칙은, 인스턴스를 만드는 용도라면 static 메서드보다 (이름 있는) 생성자를 정의하라고 권하는 규칙이에요. Stable 상태이고, 코드 수정도 자동으로 가능해요.
출처: Prefer defining constructors instead of static methods to create instances.
본문
대부분의 경우 인스턴스를 만드는 방법은 static 메서드보다 **이름 있는 생성자(named constructor)**를 쓰는 게 더 명확해요. 객체를 '만드는' 동작이라는 게 생성자로 드러나는 편이 읽는 사람 입장에서 훨씬 자연스럽거든요.
BAD — Point.polar을 static 메서드로 만들었어요.
class Point {
num x, y;
Point(this.x, this.y);
static Point polar(num theta, num radius) {
return Point(radius * math.cos(theta),
radius * math.sin(theta));
}
}
GOOD — Point.polar이라는 이름 있는 생성자로 만들었어요.
class Point {
num x, y;
Point(this.x, this.y);
Point.polar(num theta, num radius)
: x = radius * math.cos(theta),
y = radius * math.sin(theta);
}
static 메서드는 Point.polar(...)처럼 호출해야 하지만, 생성자로 만들면 Point.polar(...)이라는 그 이름 자체가 곧 인스턴스를 만드는 방법이라는 게 드러나요. 문법도 비슷해 보이는데, 생성자 쪽이 목적을 더 명확히 표현해요.
규칙 켜기
analysis_options.yaml 파일의 linter > rules 아래에 prefer_constructors_over_static_methods를 추가하면 돼요.
linter:
rules:
- prefer_constructors_over_static_methods
YAML 맵 문법으로 설정한다면 이렇게 써요.
linter:
rules:
prefer_constructors_over_static_methods: true
더 알아보기
- 이름 있는 생성자가 뭔지, 언제 쓰면 좋은지는 Dart 언어의 생성자 문서를 참고해요.