4-1.데이터뭉치(Data Clumps)

[ 2017-07.25 작성 ]

객체를 사용하여 데이터 덩어리를 대체하면 전체 코드 크기가 줄어들뿐만 아니라 프로그램 코드가 더 체계적이고 읽기 쉽고 디버그하기 쉬워집니다.

매개 변수 / 변수의 긴 목록이 반드시 데이터 클럼프를 나타내는 것은 아닙니다. 중요한 것은 다양한 값들의 존재가 데이터 덩어리로 간주된다는 사실을 친밀하고 논리적으로 관련 지을때만입니다.

※객체 지향 프로그래밍에서 객체의 목적은 이 데이터에서 수행 할 수 있는 관련 데이터(필드)와 연산(메서드)을 모두 캡슐화하는 것입니다.

sample code

public static void main(String args[]) {
    String firstName = args[0];
    String lastName = args[1];
    Integer age = new Integer(args[2]);
    String gender = args[3];
    String occupation = args[4];
    String city = args[5];
    welcomeNew(firstName,lastName,age,gender,occupation,city);
}
 
public static void welcomeNew(String firstName, String lastName, Integer age, String gender, String occupation, String city){
   System.out.printf("Welcome %s %s, a %d-year-old %s from %s who works as a%s\n",firstName, lastName, age, gender, city, occupation);
}

앞의 예에서 모든 변수는 하나의 "Person"객체로 캡슐화 될 수 있습니다. 이 객체는 그 자체로 전달 될 수 있습니다.
또한 프로그래머는 welcomeNew 메소드가 Person 클래스와 더 잘 연관되어 있다는 것을 인식하고 Person과 연관된 다른 관련 조치를 제안할 수 있습니다.

public static void main(String args[]) {
    String firstName = args[0];
    String lastName = args[1];
    Integer age = new Integer(args[2]);
    String gender = args[3];
    String occupation = args[4];
    String city = args[5];

    Person joe = new Person(firstName,lastName,age,gender,occupation,city);
    joe.welcomeNew();
    joe.work();
    
}
private static class Person{
  /* All parameters have been moved to the new Person class where they are properly grouped and encapsulated */
  String firstName;
    String lastName;
    Integer age;
    String gender;
    String occupation;
    String city;
    
    public Person(String firstName, String lastName, Integer age, String gender, String occupation, String city){
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
      this.gender = gender;
      this.occupation = occupation;
      this.city = city;
    }
    
    /* Existing functionality relating to the data can also be incorporated into the new class, reducing the risk of scope collision */
    public void welcomeNew(){
      System.out.printf("Welcome %s %s, a %d-year-old %s from %s who works as a%s\n",firstName, lastName, age, gender, city, occupation);
  }
    /* Additionally, the new class may be an opportunity for new functionality to be added */
    public void work(){
      System.out.printf("This is %s working hard on %s in %s", firstName, occupation, city);
    }
    
}

코드의 길이는 증가시켰지만 이제는 단일 Person이 다양한(겉으로 보기에는 관계가 없는) 필드가 아닌 하나의 객체로 쉽게 전달될 수 있습니다. 또한 관련 메서드를 클래스로 이동하여 각 메소드를 개별 인스턴스에서 쉽게 조작할 수 있습니다.
이러한 메소드는 더 이상 매개 변수 목록을 전달할 필요가 없습니다. 대신 객체 인스턴스 자체에 인스턴스 변수로 저장되므로 매개 변수 목록을 전달할 필요가 없습니다.

https://en.wikipedia.org/wiki/Data_Clump_Code_Smell)(