ComputerScience/프로그래밍 패러다임

객체지향 프로그래밍

dev_swan 2023. 11. 13. 23:00

✏️ 객체지향 프로그래밍

객체지향 프로그래밍(OOP, Object-Oriented Programming)은 객체들의 집합으로 프로그램의 상호 작용을 표현하며 데이터를 객체로 취급하여 객체 내부에 선언된 메서드를 활용하는 방식을 말합니다. 설계에 많은 시간이 소요되며 처리 속도가 다른 프로그래밍에 비해 상대적으로 느립니다.

 

객체 지향 프로그래밍 - https://www.linkedin.com/pulse/power-object-oriented-programming-oop-modern-software-kavidu-krishan-vgl1c/

 

예를 들어 자연수로 이루어진 배열에서 최댓값을 찾으라고 한다면 다음과 같이 로직을 구성합니다.

const ret = [1, 2, 3, 4, 5, 6];

class List {
    constructor(list) {
        this.list = list;
        this.mx = list.reduce((max, num) => (num > max ? num : max), 0);
    }

    getMax() {
        return this.mx;
    }
}

const a = new List(ret);
console.log(a.getMax()); // 6

 

🔍 객체지향 프로그래밍의 특징

 

🔴 추상화 (Abstraction)

추상화란 복잡한 시스템으로부터 핵심적인 개념 또는 기능을 간추려내는 것을 의미합니다. 자동차를 프로그래밍 상에서 표현할 때, 예를 들어, 우리는 색상, 브랜드, 최대 속도 등의 특징만을 고려할 수 있으며, 자동차의 내부 구조나 세부 부품 등의 복잡한 정보는 생략할 수 있습니다.

 

🔴 캡슐화 (Encapsulation)

캡슐화는 객체의 속성과 메서드를 하나로 묶고 일부를 외부에서 접근할 수 없도록 감추어 은닉하는 것을 말합니다. 예를 들어, 은행 계좌 객체에서 잔액을 직접 수정하지 못하게 하고, 입금과 출금 메서드만을 통해 잔액을 변경할 수 있도록 하는 것입니다.

 

🔴 상속성 (Inheritance)

상속성은 상위 클래스의 특성을 하위 클래스가 이어받아서 재사용하거나 추가, 확장하는 것을 말합니다. 코드의 재사용 측면, 계층적인 관계 생성, 유지 보수성 측면에서 중요합니다. 예를 들어, 동물 클래스에는 움직이다, 먹다와 같은 메서드가 있을 수 있으며, 이를 상속받은 개나 고양이 클래스에서 해당 메서드를 사용할 수 있습니다.

 

🔴 다형성 (Polymorphism)

다형성은 하나의 메서드나 클래스가 다양한 방법으로 동작하는 것을 말합니다. 대표적으로 오버로딩, 오버라이딩이 있습니다. 예를 들어, 도형 클래스를 상속받은 삼각형, 사각형, 원 클래스가 모두 그리다 라는 메서드를 구현할 때, 각 클래스마다 다른 방식으로 그리다 메서드를 구현할 수 있습니다.

더보기

💡 오버로딩 (Overloading)

오버로딩은 같은 이름을 가진 메서드를 여러 개 두는 것을 말합니다. 메서드의 타입, 매개변수의 유형, 개수 등으로 여러 개를 둘 수 있으며 컴파일 중에 발생하는 정적 다형성입니다.

 

class DemoOverloading {
    display(value: string): void;
    display(value: number, value2: number): void;
    display(value: boolean): void;
    display(value: any, value2?: any): void {
        if (typeof value === 'string') {
            console.log(`Single string argument: ${value}`);
        } else if (typeof value === 'number' && typeof value2 === 'number') {
            console.log(`Two number arguments: ${value}, ${value2}`);
        } else if (typeof value === 'boolean') {
            console.log(`Boolean argument: ${value}`);
        } else {
            console.log('Unknown set of arguments');
        }
    }
}

let demo = new DemoOverloading();

demo.display('Hello!'); // Single string argument: Hello!
demo.display(1, 2); // Two number arguments: 1, 2
demo.display(true); // Boolean argument: true

 

💡 오버라이딩 (Overriding)

오버라이딩은 주로 메서드 오버라이딩을 말하며 상위 클래스로부터 상속받은 메서드를 하위 클래스가 재정의하는 것을 의미합니다. 이는 런타임 중에 발생하는 동적 다향성입니다.

 

class Animal {
    speak() {
        return 'I am animal';
    }
}

class Dog extends Animal {
    speak() {
        return 'Woof woof!';
    }
}

class Cat extends Animal {
    speak() {
        return 'Meow meow!';
    }
}

const aniaml = new Animal();
console.log(aniaml.speak()); // I am animal

const dog = new Dog();
console.log(dog.speak()); // Woof woof!

const cat = new Cat();
console.log(cat.speak()); // Meow meow!

🛠 객체지향 프로그래밍 설계 원칙

객체지향 프로그래밍을 설계할 때는 SOLID 원칙을 지켜주어야 합니다. S는 단일 책임 원칙, O는 개방-폐쇄 원칙, L은 리스코프 치환 원칙, I는 인터페이스 분리 원칙, D는 의존 역전 원칙을 의미합니다.

SOLID 원칙 - https://velog.io/@wogud7587/SOLID%EB%9E%80

 

1. 단일 책임 원칙 (SRP, Single Responsibility Principle)

단일 책임 원칙은 모든 클래스는 각각 하나의 책임만을 가져야 하는 원칙입니다. 예를 들어 A라는 로직이 존재한다면 어떠한 클래스는 A에 관한 클래스여야 하고 이를 수정한다고 했을 때도 A와 관련된 수정이어야 합니다.

 

🚫 문제 상황

아래와 같은 상황에서 User 클래스는 두 가지 책임을 가지고 있습니다.

  1. 사용자 정보를 데이터베이스에 저장하는 책임
  2. 사용자 정보를 콘솔에 출력하는 책임

이러한 설계는 변경 사항이 발생할 때 문제가 될 수 있습니다. 예를 들어, 데이터베이스 저장 방식이나 출력 형식이 변경되면 User 클래스 자체를 수정해야 합니다.

class User {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    saveToDatabase() {
        console.log(`Saving ${this.name} of ${this.age} to database`);
    }

    displayToConsole() {
        console.log(`Name : ${this.name}, Age : ${this.age}`);
    }
}

const user = new User('Asher', 25);
user.saveToDatabase(); // Saving Asher of 25 to database
user.displayToConsole(); // Name : Asher, Age : 25

 

👍 단일 책임 원칙 적용

아래와 같이 User, UserDatabase, UserDisplay 각각의 클래스는 자신의 책임에만 집중하며, 한 클래스의 변경이 다른 클래스에 영향에 미치는 일이 크게 줄어듭니다.

class User {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}

class UserDatabase {
    save(user) {
        console.log(`Saving ${user.name} of ${user.age} to database`);
    }
}

class UserDisplay {
    display(user) {
        console.log(`Name : ${user.name}, Age : ${user.age}`);
    }
}

const user = new User('Asher', 25);
const userDatabase = new UserDatabase();
const userDisplay = new UserDisplay();

userDatabase.save(user);
userDisplay.display(user);

 

 

2. 개방-폐쇄 원칙 (OCP, Open Closed Principle)

개방-폐쇄 원칙은 유지 보수 사항이 생긴다면 코드를 쉽게 확장할 수 있도록 하고 수정할 때는 닫혀 있어야 하는 원칙입니다. 즉, 기존의 코드는 잘 변경하지 않으면서도 확장은 쉽게 할 수 있어야 합니다.

 

🚫 문제 상황

아래와 같이 사각형의 넓이를 계산하는 기능을 가진 클래스가 있다고 가정했을 때, 원의 넓이도 계산하고 싶다면 AreaCalculato와 Rectangle을 수정해야 합니다.

class Rectangle {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }

    area() {
        return this.width * this.height;
    }
}

class AreaCalculator {
    constructor(rectangles) {
        this.rectangles = rectangles;
    }

    totalArea() {
        return this.rectangles.reduce((sum, rectangle) => sum + rectangle.area(), 0);
    }
}

const rectangle1 = new Rectangle(10, 5);
const rectangle2 = new Rectangle(8, 5);
const calculator = new AreaCalculator([rectangle1, rectangle2]);
console.log(calculator.totalArea()); // 90

 

👍 개방-폐쇄 원칙 적용

아래와 같이 설계하면 새로운 도형을 추가하더라도 Shape를 상속받아 확장하는 클래스만 만들면 되고, AreaCalculator는 변경할 필요가 없습니다.

class Shape {
    area() {
        throw new Error('Area 메서드는 상속 받는 클래스에서 구현되어야 합니다.');
    }
}

class Rectangle extends Shape {
    constructor(width, height) {
        super();
        this.width = width;
        this.height = height;
    }

    area() {
        return this.width * this.height;
    }
}

class Circle extends Shape {
    constructor(radius) {
        super();
        this.radius = radius;
    }

    area() {
        return Math.PI * this.radius * this.radius;
    }
}

class AreaCalculator {
    constructor(shapes) {
        this.shapes = shapes;
    }

    totalArea() {
        return this.shapes.reduce((sum, shape) => sum + shape.area(), 0);
    }
}

const rectangle = new Rectangle(10, 5);
const circle = new Circle(3);
const calculator = new AreaCalculator([rectangle, circle]);
console.log(calculator.totalArea()); // 약 78.3

 

3. 리스코프 치환 원칙 (LSP, Liskov Substitution Principle)

리스코프 치환 원칙은 프로그램의 객체는 프로그램의 정확성을 깨뜨리지 않으면서 하위 타입의 인스턴스로 바꿀 수 있어야 하는 것을 의미합니다.

 

클래스는 상속이 되기 마련이고 부모, 자식이라는 계층 관계가 만들어집니다. 이때 부모 객체에 자식 객체를 넣어도 시스템이 문제없이 돌아가게 만드는 것을 말합니다.

 

🚫 문제 상황

아래의 코드에서는 Ostrich는 Brid를 확장하지만 fly 메서드를 재정의하여 Can’t fly 오류를 발생 시킵니다. 이로 인해 makeBridFly 함수는 Brid의 모든 하위 클래스에 안전하게 사용할 수 없게 됩니다.

class Bird {
    fly() {
        console.log("I can fly");
    }
}

class Ostrich extends Bird {
    fly() {
        throw new Error("Can't fly");
    }
}

function makeBirdFly(bird) {
    bird.fly();
}

const myBird = new Bird();
const myOstrich = new Ostrich();

makeBirdFly(myBird);  // I can fly
makeBirdFly(myOstrich);  // Error: Can't fly

 

👍 리스코프 치환 원칙 적용

아래의 코드는 Ostrich는 비행할 수 없는 새의 범주인 NonFlyingBird로부터 상속받으므로 fly메서드는 I can’t fly를 출력합니다.

class Bird {
    fly() {
        console.log('I can fly');
    }
}

class NonFlyingBird extends Bird {
    fly() {
        console.log("I can't fly");
    }
}

class Ostrich extends NonFlyingBird {}

function makeBirdFly(bird) {
    bird.fly();
}

const myBird = new Bird();
const myOstrich = new Ostrich();

makeBirdFly(myBird); // I can fly
makeBirdFly(myOstrich); // I can't fly

 

4. 인터페이스 분리 원칙 (ISP, Interface Segregation Principle)

인터페이스 분리 원칙은 클래스는 자신이 사용하지 않는 인터페이스는 구현하지 않아야 한다는 것을 의미합니다. 다시 말해, 한 클래스가 필요로 하지 않는 메서드를 포함한 인터페이스에 의존하도록 만들면 안 된다는 것입니다.

 

예를 들어, Worker라는 인터페이스가 있고 이 인터페이스에는 work와 eat 두 메서드를 정의하고 있습니다. 만약 Robot이라는 클래스가 Worker인터페이스를 구현한다면, eat은 로봇에게 필요 없는 메서드가 되기 때문에 이는 Worker라는 인터페이스를 두 개의 인터페이스로 분리하여 불필요한 eat구현하지 않아도 됩니다.

 

🚫 문제 상황

아래 코드에서 Robot은 Worker클래스를 상속받지만, eat 메서드는 로봇에게 적절하지 않습니다. 그럼에도 불구하고 Robot은 eat메서드를 재정의해야 합니다.

class Worker {
    work() {
        console.log("Let's work");
    }

    eat() {
        console.log("Let's eat");
    }
}

class Robot extends Worker {
    eat() {
        throw new Error("Robots can't eat");
    }
}

 

👍 인터페이스 분리 원칙 적용

아래 코드에서 Eater클래스는 eat메서드만을 포함하며, Human클래스는 Worker와 Eater의 기능을 모두 사용합니다. 이렇게 하면 각 클래스와 메서드가 단일 책임 원칙과 인터페이스 분리 원칙을 더 잘 따르게 됩니다.

class Worker {
    work() {
        console.log("Let's work");
    }
}

class Eater {
    eat() {
        console.log("Let's eat");
    }
}

class Human extends Worker {
    constructor() {
        super();
        this.eater = new Eater();
    }
}

class Robot extends Worker {}

 

5. 의존 역전 원칙 (DIP, Dependency Inversion Principle)

의존 역전 원칙은 고수준 모듈은 저수준 모듈에 의존하면 안 된다는 것을 의미합니다. 즉, 자신보다 변하기 쉬운것에 의존하던 것을 추상화된 인터페이스나 상위 클래스를 두어 변하기 쉬운 것의 변화에 영향을 받지 않게 하는 원칙을 의미합니다.

 

🚫 문제 상황

아래 코드에서 Switch클래스는 LightBulb클래스에 직접적으로 의존합니다. 이로 인해 둘 사이에 강한 결합성이 생기게 됩니다.

class LightBulb {
    turnOn() {
        console.log('Lightbulb is On');
    }

    turnOff() {
        console.log('Lightbulb is Off');
    }
}

class Switch {
    constructor(bulb) {
        this.bulb = bulb;
    }

    operate() {
        const isOn = this.bulb === 'on';
        if (isOn) {
            this.bulb.turnOff();
        } else {
            this.bulb.turnOn();
        }
    }
}

 

👍 의존 역전 원칙 적용

이제 Switch클래스는 구체적인 LightBulb나 Fan에 의존하지 않고, 추상화된 Device에만 의존합니다. 이로써 Switch는 다양한 장치와 함께 작동할 수 있게 되었습니다.

class Device {
    turnOn() {}
    turnOff() {}
}

class LightBulb extends Device {
    turnOn() {
        console.log('Lightbulb is On');
    }

    turnOff() {
        console.log('Lightbulb is Off');
    }
}

class Fan extends Device {
    turnOn() {
        console.log('Fan is On');
    }

    turnOff() {
        console.log('Fan is Off');
    }
}

class Switch {
    constructor(device) {
        this.device = device;
    }

    operate() {
        // 예시
        const isOn = this.device.state === 'on';
        if (isOn) {
            this.device.turnOff();
        } else {
            this.bulb.turnOn();
        }
    }
}