자바/클린 코드

클린코드 6장 - 객체와 자료구조

끄적끄적 2022. 5. 20. 12:01

6장에서는 자료구조와 객체의 두가지 개념을 소개한다.
자료구조는 자료를 그대로 공개하며 별다른 함수를 제공하지 않는게 좋다. VO나 DTO 객체를 의미한다.
객체는 추상화 뒤로 자료를 숨긴 채 자료를 다루는 함수만 공개한다.

자료구조 형식의 클래스

public class Point { 
  public double x; 
  public double y;
}

추상적인 객체 방식의 클래스

public interface Point {
  double getX();
  double getY();
  void setCartesian(double x, double y); 
  double getR();
  double getTheta();
  void setPolar(double r, double theta); 
}

(자료구조를 사용하는) 절차적인 코드는 기존 자료 구조를 변경하지 않으면서 새 함수를 추가하기 쉽다.
반면, 객체지향 코드는 기존 함수를 변경하지 않으면서 새 클래스를 추가하기 쉽다.

절차적인 코드는 새로운 자료구조를 추가하기 어렵다. 그러려면 모든 함수를 고쳐야 한다.
객체 지향코드는 새로운 함수를 추가하기 어렵다. 모든 클래스를 고쳐야 한다.

구체적인 Vehicle 클래스

public interface Vehicle { 
  double getFuelTankCapacityInGallons(); 
  double getGallonOfGasoline();
}

추상적인 Vehicle 클래스

public interface Vehicle { 
  double getPercentFuelRemaining(); 
}

위에서 사용자는 자동차의 연료상태를 하나하나 읽을 필요가 없이, 남아있는 양만 알면 된다. 구체적인 내용을 제시하기보다 추상적으로 사용할 수 있게 해 주는게 좋다.

절차적인 도형

public class Square { 
  public Point topLeft; 
  public double side;
}

public class Rectangle { 
  public Point topLeft; 
  public double height; 
  public double width;
}

public class Circle { 
  public Point center; 
  public double radius;
}

public class Geometry {
  public final double PI = 3.141592653589793;

  public double area(Object shape) throws NoSuchShapeException {
    if (shape instanceof Square) { 
      Square s = (Square)shape; 
      return s.side * s.side;
    } else if (shape instanceof Rectangle) { 
      Rectangle r = (Rectangle)shape; 
      return r.height * r.width;
    } else if (shape instanceof Circle) {
      Circle c = (Circle)shape;
      return PI * c.radius * c.radius; 
    }
    throw new NoSuchShapeException(); 
  }
}

다형성을 적용한 도형

public class Square implements Shape { 
  private Point topLeft;
  private double side;

  public double area() { 
    return side * side;
  } 
}

public class Rectangle implements Shape { 
  private Point topLeft;
  private double height;
  private double width;

  public double area() { 
    return height * width;
  } 
}

public class Circle implements Shape { 
  private Point center;
  private double radius;
  public final double PI = 3.141592653589793;

  public double area() {
    return PI * radius * radius;
  } 
}

 

디미터 법칙
디미터 법칙은 "클래스 C의 메서드 f는 다음과 같은 객체의 메서드만 호출해야 한다"고 주장한다.

다음과 같은 코드를 기차 충돌이라고 부른다.

final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();

위 코드는 한줄로 이어진 기차처럼 보이는데, 아래와 같이 나누는게 명확하다.

Options opts = ctxt.getOptions();
File scratchDir = opts.getScratchDir();
final String outputDir = scratchDir.getAbsolutePath();

잡종구조
절반은 자료구조 처럼 공개변수가 있고, 절반은 객체러럼 설정함수가 있는 방식은 어중간하다. 이부분은 최근 객체지향의 변화로 좀 다시 생각해볼 부분이다.

 

반응형