객체와 자료 구조

ppby·2021년 9월 14일
0

ppby.TIL

목록 보기
24/26
post-thumbnail

책의 예시들을 typescript로 작성하였습니다. 의미가 안 맞을 수 있지만 최대한 비슷한 느낌으로 작성하려 노력했습니다🥺


1. 자료구조 vs 객체

자료구조(Data Structure)

  • 데이터 그 자체
  • 자료를 공개한다.
  • 변수 사이에 조회 함수와 설정 함수로 변수를 다룬다고 객체가 되지 않는다.(gettersetter)
// 자료 구조
interface Vehicle {
  getFuelTankCapacityInGallons(): number; // 연료탱크 용량(갤런 단위)
  getGallonsOfGasoline(): number; // 가솔린 (갤런 단위)
}

// 멤버 변수를 그냥 준다.
class Car implements Vehicle {
	fuelTankCapacityInGallons: number = 0 // 초기값
	gallonsOfGasoline: number = 0 // 초기값

  getFuelTankCapacityInGallons() {
    return this.fuelTankCapacityInGallons;
  }

  getGallonsOfGasoline() {
    return this.gallonsOfGasoline;
  }
}

객체(Object)

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

class Car implements Vehicle {
  constructor(public fuelTankCapacityInGallons: number, public gallonsOfGasoline: number) {
    if (this.fuelTankCapacityInGallons <= 0) {
      throw new Error('fuelTankCapacityInGallons must be greater than zero');
    }
  }

  getPercnetFuelRemain(): number {
    return (this.gallonsOfGasoline / this.fuelTankCapacityInGallons) * 100;
  }
}
  • 만약 휴대폰 배터리처럼 실제 수치는 중요하지 않고, 퍼센트만 중요한 경우 → 객체로 표현
  • 그 안의 데이터는 중요하지 않고 비즈니스 로직에 맞는 값만 표현하면 되기 때문

자료/객체 비대칭

  • 절차적인 코드 : 기존 자료 구조를 변경하지 않으면서 새 함수를 추가하기 쉽다.

  • 절차적인 코드는 새로운 자료 구조를 추가하기 어렵다. → 함수를 고쳐야 하기 때문

    // 절차적인 코드
    class Square {
      constructor(public topLeft: number, public side: number) {}
    }
    class Rectangle {
      constructor(public width: number, public height: number) {}
    }
    class Circle {
      constructor(public center: number, public radius: number) {}
    }
    
    class Geometry {
      PI: number = Math.PI;
    
      area(shape: object): number {
        if (shape instanceof Square) {
          const s: Square = new Square(shape.topLeft, shape.side);
          return s.side * s.side;
        } else if (shape instanceof Rectangle) {
          const r: Rectangle = new Rectangle(shape.width, shape.height);
          return r.height * r.width;
        } else if (shape instanceof Circle) {
          const c: Circle = new Circle(shape.center, shape.radius);
          return this.PI * c.radius * c.radius;
        }
    
        throw new Error('No such Shape exception');
      }
    }
  • 객체 지향 코드 : 기존 함수를 변경하지 않으면서 새 클래스를 추가하기 쉽다. → 하지만 함수를 추가해야 한다

    // **객체 지향 코드**
    interface Shape {
      area():number
    }
    
    class Square implements Shape {
      constructor(private topLeft: number, private side: number) {}
      area():number {
        return this.side * this.side;
      }
    }
    
    class Rectangle implements Shape {
      constructor(private topLeft: number,private width: number, private height: number) {}
      area():number {
        return this.height * this.width;
      }
    }
    
    class Circle implements Shape {
      private PI: number = Math.PI;
      constructor(public center: number, public radius: number) {}
      area():number {
        return this.PI * this.radius * this.radius;
      }
    }

상황에 맞는 선택을 하면 된다.

  • 자료구조를 사용하는 절차적인 코드는 기본 자료 구조를 변경하지 않으면서 새 함수를 추가하기 쉽다.
  • 절차적인 코드는 새로운 자료 구조를 추가하기 어렵다. → 모든 함수를 고쳐야 함
  • 객체 지향 코드는 기존 함수를 변경하지 않으면서 새 클래스를 추가하기 쉽다.
  • 객체 지향 코드는 새로운 함수를 추가하기 어렵다. → 모든 클래스를 고쳐야 한다.

2. 객체 - 디미터 법칙

  • 모듈은 자신이 조작하는 객체의 속사정을 몰라야 한다는 법칙
  • 객체 → 내부 구조를 숨겨야 함
  • 자료 구조 → 당연히 내부 구조를 노출
  • 휴리스틱 : 경험에 기반하여 문제를 해결하기 위해 발견한 방법 의사결정을 단순화하기 위한 법칙들 → 경험적으로 만들어낸 법칙

3. 자료 전달 객체(DTO) - 자료 구조

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

  • 로직 없이 필드만 갖는다.
  • 일반적으로 클래스명이 Dto(or DTO)로 끝난다.
  • getter/setter 를 갖기도 한다.
  • 흔히 DTO는 데이터베이스에 저장된 가공되지 않은 정보를 애플리케이션 코드에서 사용할 객체로 변환하는 일련의 단계에서 가장 처음으로 사용하는 구조체
  • 활성 레코드
profile
(ง •̀_•́)ง 

0개의 댓글