#concept #development
> [!Note]
> ソフトウェアの振る舞いは、既存の成果物を変更せず拡張できるようにすべきである
今後の変更に合わせてコンポーネントを分割する。
また、そのコンポーネントに対する階層構造を明確に分ける。
![[スクリーンショット 2022-08-21 16.46.02.png|400]]
以下はOCPに反する
```dart
class SalaryService {
int calculateSalary(Employee employee) {
switch (employee.grade) {
case 1:
return employee.grade * 1000;
case 2:
return employee.grade * 1500;
...
}
}
Future<void> payment(Employee employee) {
final salary = calculateSalary(employee)
paymentService.payment(salary)
}
}
```
この例の場合、`Employee`の`grade`が増えると関数を変更する必要がある。
以下のようにインターフェースを実装することで、既存コードに変更することなく実現が可能になる
```dart
abstract class Employee {
final String grade;
final int salaryRate;
int calculateSalary()
}
class Engineer extends Employee {
final String grade = 3;
final int salaryRate = 1.1;
int calculateSalary() {
return grade * saralyRate;
}
}
class SalaryService {
Future<void> payment(Employee employee) {
final salary = employee.calculateSalary();
paymentService.payment(salary);
}
}
```