2 minute read

객체와 자료구조로 데이터 표현하기

목차

  1. 자료구조 vs 객체
  2. 객체 - 디미터 법칙
  3. DTO
  4. Active Record

1. 자료구조와 객체

자료구조 (Data Structure) vs 객체(Object)

단순히 변수(field) 사이에 함수 계층을 넣는다고 구현이 감춰지는것은 아니다. 구현을 감추려면 추상화가 필요하다.

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

자료를 세세하게 공개하기 보단 추상적인 개념으로 표현하는것이 좋다.

일단 자료 구조와 객체를 아래 예를 통해 알아보자

자료구조

  • 데이터 그 자체
  • 자료를 공개한다.
  • 변수 사이에 조회 함수와 설정 함수로 변수를 다룬다고 객체가 되지 않는다. (getter, setter)
// 구체적인 Vehicle Interface
public interface Vehicle {
    double getFuelTankCapacityInGallons(); // 연료 탱크 용량
    double getGallonsOfGasoline(); //
    
}

public class Car implements Vehicle {
    double fuelTankCapacitiInGallons;
    double gallonsOfGasoline;

    public double getFuelTankCapacityInGallons() {
        return this.fuelTankCapacitiInGallons;
    }

    public double getGallonsOfGasoline() {
        return this.gallonsOfGasoline;
    }
}

객체로서의 vehicle

객체 (Object)

  • 비즈니스 로직과 관련
  • 자료를 숨기고 추상화 한다.
  • 자료를 다루는 함수만 공개한다.
  • 추상 인터페이스를 제공해 사용자가 구현을 모른 채 자료의 핵심을 조작할 수 있다.
// 추상적인 Vehicle Interface
public interface Vehicle {
    double PercentFuelRemain();
}


public class Car implements Vehicle {

    double fuelTankCapacitiInGallons;
    double gallonsOfGasoline;

    public Car(double fuelTankCapacitiInGallons, double gallonsOfGasoline) {
        if (fuelTankCapacitiInGallons <= 0) {
            throw new IllegalArgumentException("error");
        }

        public double getPercentFuelRemain() {
            return this.gallonsOfGasoline / this.fuelTankCapacitiInGallons * 100;
        }
    }
 
}

자료 / 객체의 차이

객체와 자료 구조 사이에는 서로의 장단점이 명확하게 존재한다.

  • 객체: 추상화 뒤로 자료를 숨긴 채 자료를 다루는 함수만 공개한다.
  • 자료 구조: 자료를 그대로 공개하며 별다른 함수를 제공하지 않는다.

추가로 예제를 살펴보자

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.1415926;

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

        throw new NoSuchShapeException();
    }
}
  • 위 자료구조 코드의 이점
    • Geometry 클래스에 새로운 함수를 추가할 때 도형 클래스는 수정되지 않는다.
  • 위 자료구조 코드의 단점
    • 새로운 도형이 추가되면 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 Square implements Shape {
    private Point center;
    private double radius;
    public final double PI = 3.1415926

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

  • 객체 지향적 코드 이점
    • 기존 코드나 함수를 수정하지 않고 새로운 클래스를 추가하기 쉽다.
  • 객체 지향적 코드 단점
    • 새로운 함수를 추가하기 위해서는 모든 클래스가 수정될 수 있다.

디미터의 법칙

모듈은 자신이 조작하는 객체의 속사정을 몰라야 한다.

객체는 조회 함수로 내부 구조를 공개하면 안된다.

클래스 C의 메서드 f는 다음과 같은 객체의 메서드만 호출해야 한다.

  • 클래스 c
  • 자신이 생성한 객체
  • 자신의 인수로 넘어온 객체
  • c 인스턴스 변수에 저장된 객체

기차 충돌

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

위와 같이 메서드 체이닝한 코드를 기차 충돌이라 부르는데. 코드가 조잡해지기 떄문에 이것을 나누는게 좋다.

## DTO (Data Transfer Object) = 자료구조

다른 계층 간 데이터를 교환할 떄 사용

  • __로직__없이 필드만 갖는다.
    • 데이터를 파싱하는건??
  • 일반적으로 클래스명이 Dto로 끝난다.
  • getter/setter를 갖기도 한다.

*Beans Java Beans: 데이터 표현이 목적인 자바 객체

  • 멤버 변수는 private 속성이다.
  • getter setter 를 갖는다.

DTO의 사용범위에 대하여

Categories:

Updated: