객체지향 설계의 5대 원칙을 쉽게 이해하기 SOLID

✨ 개요

SOLID 원칙은 객체지향 프로그래밍의 기본이자, 유지보수성과 확장성을 갖춘 소프트웨어 설계의 핵심 지침입니다.

이 다섯 가지 원칙은 개발자가 더 나은 코드 구조를 만들고, 변화에 유연하게 대응하도록 도와줍니다.


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

class ReportPrinter {
  fun print(report: Report) { /* 출력 로직 */ }
}
class ReportSaver {
  fun save(report: Report) { /* 저장 로직 */ }
}

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

interface Shape { fun draw() }
class Circle : Shape { override fun draw() { /* ... */ } }
class Rectangle : Shape { override fun draw() { /* ... */ } }
fun render(shapes: List<Shape>) {
  shapes.forEach { it.draw() }
}

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

open class Rectangle {
  var width: Int = 0
  var height: Int = 0

  open fun setWidth(w: Int) { width = w }
  open fun setHeight(h: Int) { height = h }
  fun getArea(): Int = width * height
}

class Square : Rectangle() {
  override fun setWidth(w: Int) {
    width = w
    height = w // 정사각형은 너비 = 높이
  }

  override fun setHeight(h: Int) {
    width = h
    height = h // 정사각형은 높이 = 너비
  }
}

fun printArea(rect: Rectangle) {
  rect.setWidth(5)
  rect.setHeight(4)
  println("Expected area: 20, Actual area: ${rect.getArea()}")
}

fun main() {
  printArea(Rectangle())  // 출력: Expected area: 20, Actual area: 20
  printArea(Square())     // 출력: Expected area: 20, Actual area: 16 → LSP 위반
}

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

interface Printable { fun print() }
interface Scannable { fun scan() }
class Printer : Printable
class MultiFunctionPrinter : Printable, Scannable

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

interface AuthService { fun login() }
class GoogleAuth : AuthService { override fun login() { /* Google 로그인 */ } }
class LoginManager(private val authService: AuthService) {
    fun authenticate() = authService.login()
}

6.🧠 결론



Related Posts