프로그래밍/클린 코드

[클린코드] 6장. 객체와 자료구조

2KB 2020. 9. 27. 01:36

진정한 의미의 객체는 추상 인터페이스를 제공해 사용자가 구현을 모른 채 자료의 핵심을 조작할 수 있어야 한다.

자료구조는 자료를 그대로 제공하며, 다른 함수를 제공하지 않는다.

 

절자지향적 코드

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();
 }

절차지향적 코드에서 Geometry 클래스에 다른 함수를 추가한다고 생각해보면,

다른 도형 클래스(자료구조)에는 전혀 영향을 미치지 않는다.

하지만, 새로운 도형 클래스(자료구조)를 추가하게 될 경우에는 관련된 모든 함수에 추가적인 코드가 필요하게 된다.

 

 

객체지향적 코드

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;
 }
}

 

위의 예제에서 보이는 바와 같이 객체지향적 코드에서는

추상화(Interface, abstract)에 의해 기존 함수의 구조를 변경하지 않으면서 새 클래스를 추가하기가 쉬워진다.

하지만, Shape Class(Interface, abstact) 에 어떠한 함수를 추가하게 되면,

하위 모든 클래스에 해당 함수에 대한 구현이 필요하게 된다.

 

 

디미터의 법칙

 - 자신이 사용하는 객체의 내부에 대해서는 알면 안된다.

 - 객체는 자신의 데이터를 감추고, 함수만 노출해야 한다.

 - 객체는 자신의 구조를 접근 함수를 통해 노출하면 안된다.

 

예) 클래스 C 의 함수 f는 다음과 같은 객체의 메소드만 호출해야 한다.

 - C

 - f가 생성한 객체

 - f에 인자로 전달된 객체

 - C의 인스턴스 변수로 선언된 객체