우리가 메모장이 아니라 VScode와 같은 IDE에서 프로그램을 개발하는 가장 큰 이유 중 하나는 자동완성 기능일 겁니다.
Code Generation기능은 자동완성 기능을 한발 더 발전시킨 것 입니다. 기존의 자동완성 기능이 For문을 자동 완성 시키는 수준에 그쳤다면, Code Generation은 몇 줄의 코드로 우리가 설정한 코드를 자동으로 만들어 줍니다.
해당 기능이 가장 활발하게 이용되는 곳은 Model 클래스를 만들 때 입니다.
먼저 Code Generation 없이 Model 클래스를 한번 만들어 보겠습니다.
이때 프로그래머는 다음의 구현을 직접 작성해야 합니다
class Person {
final String name;
final int age;
Person({required this.name, required this.age});
Person copyWith({String? name, int? age}) {
return Person(
name: name ?? this.name,
age: age ?? this.age,
);
}
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is Person &&
other.name == name &&
other.age == age;
}
int get hashCode => name.hashCode ^ age.hashCode;
}
위 코드를 보고 Freezed 제작자는 생각했습니다.
“생각해보니, 모델이 가진 변수를 제외한 나머지는 내가 모델을 만들 때마다 반복적으로 작성하는 코드잖아? 그렇다면 모델의 Property만 만들고 나머지 코드는 자동으로 만들 수 없을까?”
이런 아이디어에서 탄생한 것이 바로 Dart에서 가장 유명한 Code Generation 패키지인 Freezed입니다.
다음 단락에서는 Freezed를 이용하여 코드를 자동으로 만들어 보도록 하겠습니다.
이후 제작자는 Freezed 이용하여 이용해 똑같은 User 클래스를 만들었습니다.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'person.freezed.dart';
class Person with _$Person {
const factory Person({
required String name,
required int age,
}) = _Person;
}
‘person.freezed.dart'
에 만들어 집니다.// person.freezed.dart
part of 'person.dart';
abstract class $Person {
const $Person();
String get name;
int get age;
Person copyWith({String? name, int? age});
}
class _$Person implements $Person {
const _$Person({required this.name, required this.age});
final String name;
final int age;
String toString() {
return 'Person(name: $name, age: $age)';
}
bool operator ==(dynamic other) {
return identical(this, other) ||
(other is Person &&
other.name == this.name &&
other.age == this.age);
}
int get hashCode {
return name.hashCode ^ age.hashCode;
}
_$Person copyWith({String? name, int? age}) {
return _$Person(
name: name ?? this.name,
age: age ?? this.age,
);
}
}