`use_enums` 린트 규칙: enum처럼 동작하는 클래스는 enum으로
use_enums 린트 규칙: enum처럼 동작하는 클래스는 enum으로
use_enums는 enum처럼 행동하는 클래스가 있을 때 그걸 enum으로 선언하도록 알려주는 린트 규칙이에요. 열거형처럼 보이는 클래스는 enum으로 선언하는 게 더 자연스럽고 Dart의 의도와도 잘 맞아요.
출처: use_enums
본문
설명
열거형처럼 보이는 클래스는 enum으로 선언하세요. 적절한 곳에서는 enum을 사용하는 게 좋아요. enum으로 바꿀 후보가 되는 클래스는 다음 조건을 모두 만족하는 클래스예요.
- 구체적(concrete)이다.
- private이거나, private 생성 생성자(generative constructor)만 가진다.
- 클래스 자신과 같은 타입의
static const필드를 둘 이상 가진다. - 생성 생성자가 그 static 필드들의 초기화 표현식의 최상위에서만 호출된다.
hashCode,==,values,index를 정의하지 않는다.Object외에 다른 클래스를 상속하지 않는다.- 정의하는 라이브러리 안에 하위 클래스가 없다.
이런 enum을 만들고 사용하는 방법에 대해 더 알고 싶다면 'Declaring enhanced enums' 문서를 확인해 보세요.
BAD:
class LogPriority {
static const error = LogPriority._(1, 'Error');
static const warning = LogPriority._(2, 'Warning');
static const log = LogPriority._unknown('Log');
final String prefix;
final int priority;
const LogPriority._(this.priority, this.prefix);
const LogPriority._unknown(String prefix) : this._(-1, prefix);
}
고정된 LogPriority 값들을 static const로 만들어 놓은, 전형적인 enum-처럼-보이는-클래스예요. 조건을 꽤 만족하니 enum으로 바꿀 후보예요.
GOOD:
enum LogPriority {
error(1, 'Error'),
warning(2, 'Warning'),
log.unknown('Log');
final String prefix;
final int priority;
const LogPriority(this.priority, this.prefix);
const LogPriority.unknown(String prefix) : this(-1, prefix);
}
똑같은 로직을 enum으로 깔끔하게 옮긴 모습이에요. 네이밍 생성자(named constructor)인 unknown 덕분에 log.unknown('Log') 같은 표기도 그대로 가능해요.
활성화하기
use_enums 규칙을 켜려면 analysis_options.yaml 파일의 linter > rules에 use_enums를 추가해요.
linter:
rules:
- use_enums
YAML 맵 문법을 쓴다면 linter > rules 아래에 use_enums: true를 넣으면 돼요.
linter:
rules:
use_enums: true