규칙 8 : 3개 이상의 인스턴스 변수를 가진 클래스를 사용하지 않는다. (No classed with more than two instance variables)

핵심 아이디어

  • 클래스가 3개 이상의 인스턴스 변수를 가지면, 책임이 불분명해지고, 응집력이 떨어집니다.

  • 두 개까지만 인스턴스 변수를 사용하여 클래스를 단순화하고, 책임 분리를 명확히 합니다.

Before : Customer 클래스 (3개 이상의 인스턴스 변수)

class Customer {
  String firstName;
  String lastName;
  String customerId;

  Customer({required this.firstName, required this.lastName, required this.customerId});

  void displayCustomerInfo() {
    print('Customer: $firstName $lastName, ID: $customerId');
  }
}

After : 리팩토링 코드 (두 개의 클래스 사용)

  • customerId는 두 가지 방식으로 처리할 수 있습니다:

  1. 원시값 그대로 사용: customerIdint 타입으로 직접 사용하여 간단하게 처리할 수 있습니다.

  2. 값 객체(Value Object)로 처리: customerId를 별도의 클래스로 감싸, 유효성 검사나 추가 로직을 포함시켜 값 객체로 처리할 수 있습니다.

저희는 규칙 3 (원시값과 문자열의 포장) 에 따라 원시값을 포장하여 객체 지향적인 방식으로 관리하겠습니다.

class CustomerName {
  String firstName;
  String lastName;

  CustomerName({required this.firstName, required this.lastName});

  void displayName() => print('Customer Name: $firstName $lastName');
}

class CustomerId {
  int id;

  CustomerId(this.id);

  void displayId() => print('Customer ID: $id');
}

class Customer {
  CustomerId customerId;
  CustomerName name;

  Customer({required this.customerId, required this.name});

  void displayCustomerInfo() {
    name.displayName();
    customerId.displayId();
  }
}
  1. CustomerName 클래스를 만들어 firstNamelastName을 관리.

  2. CustomerId 클래스를 만들어 customerId를 관리.

사용 예시

void main() {
  var customerName = CustomerName(firstName: 'John', lastName: 'Doe');
  var customerId = CustomerId(12345);
  var customer = Customer(customerId: customerId, name: customerName);
  
  customer.displayCustomerInfo();
}

개선된 점

  • 책임 명확화: 클래스를 쪼개어 각 클래스가 명확한 책임만 가지도록 하여 SRP를 준수합니다.

  • 복잡성 감소: 인스턴스 변수를 분리하여 클래스의 복잡성을 줄이고, 가독성을 향상시킵니다.

  • 유지보수 용이: 클래스를 간결하게 만들면 코드 변경이나 확장이 용이해져 유지보수가 쉬워집니다.

Last updated