행위

파이썬 클래스 설계방법

DB CAFE

Dbcafe (토론 | 기여)님의 2020년 9월 23일 (수) 09:54 판 (SRP(Single responsibility principle) 단일 책임 원칙)
thumb_up 추천메뉴 바로가기


1 클래스 설계 방법론[편집]

1.1 5가지 클래스 설계의 원칙 (S.O.L.I.D)[편집]

  1. S - SRP(Single responsibility principle) 단일 책임 원칙
  2. O - OCP(Open Closed Principle) 개방 - 폐쇄 원칙
  3. L - LSP(Liskov Substitusion Principle) 리스코프 치환 법칙
  4. I - ISP(Interface Segregation Principle) 인터페이스 분리 원칙
  5. D - DIP(Dependency Inversion Principle) 의존성 역전 법칙

출처) https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design

1.3 SRP(Single responsibility principle) 단일 책임 원칙[편집]

  1. 클래스는 단 한개의 책임을 가져야 함 (클래스를 수정할 이유가 오직 하나)
    예: 계산기 기능 구현시, 계산을 하는 책임과 GUI를 나타낸다는 책임을 서로 분리하여, 각각 클래스로 설계
  2. 실제 애매한 부분이 많이 존재함, 가급적 설계시 고려하면 좋음.
    1. 나쁜 예
      1. 학생성적과 수강하는 코스를 한개의 class에서 다루는 예
      2. 한 클래스에서 두개의 책임을 갖기 때문에, 수정이 용이하지 않다.
class StudentScoreAndCourseManager(object):
    def __init__(self):
        scores = {}
        courses = {}
        
    def get_score(self, student_name, course):
        pass
    
    def get_courses(self, student_name):
        pass
    1. 변경 예
      1. 각각의 책임을 한개로 줄여서, 각각 수정이 다른 것에 영향을 미치지 않도록 함
class ScoreManager(object):
    def __init__(self):
        scores = {}
        
    def get_score(self, student_name, course):
        pass
    
    
class CourseManager(object):
    def __init__(self):
        courses = {}
    
    def get_courses(self, student_name):
        pass