Menu
Coddy logo textTech

개방 폐쇄 원칙

Coddy의 Clean Code - Python으로 더 나은 코드 작성하기 코스 레슨. 28개 중 23번째.

"소프트웨어 개체는 확장에는 열려 있어야 하지만, 수정에는 닫혀 있어야 한다."

이 원칙은 모든 함수, 모듈 또는 class가 코드 자체를 수정하지 않고도 동작을 확장할 수 있어야 한다는 것을 말합니다.  

TxtConvertor class가 있고, 이 class가 txt file을 json 또는 xml로 변환한다고 가정해 봅시다.

class TxtConvertor:
	def convert_to_json(self, file):
		print("converts file to json")
	
	def convert_to_xml(self, file):
		print("converts file to xml")

이 구조는 개방-폐쇄 원칙을 위반합니다.

왜 그럴까요?

예를 들어 txt file에서 html로 변환하는 기능을 추가하려면 기존 class를 수정해야 합니다(폐쇄 원칙 위반).

그렇다면 어떻게 해야 할까요?

이 예제에서 한 가지 해결 방법은 주요 함수를 포함하는 추상 class를 만드는 것입니다.

from abc import ABC, abstractmethod

class TxtConvertor(ABC):
	@abstractmethod
	def convert(self, file):
		pass

class TxtConvertorToJson(TxtConvertor):
	...

.
.
.

abc library는 Python에서 추상 기반 class를 지원합니다. 자세한 내용은 여기에서 확인할 수 있습니다.

challenge icon

챌린지

중급

주어진 예제를 수정하여 Open-Closed 원칙을 적용하고, txt를 html로 변환할 수 있는 변환기를 추가하세요.

  1. 추상 클래스 TxtConvertor를 생성하세요.
  2. TxtConvertor를 상속하고 변환기를 구현하는 TxtConvertorToJson, TxtConvertorToXML, TxtConvertorToHTML 클래스를 생성하세요(위 예제와 같이).

직접 해보기

class TxtConvertor:
	def convert_to_json(self, file):
		print("converts file to json")
	
	def convert_to_xml(self, file):
		print("converts file to xml")

Clean Code - Python으로 더 나은 코드 작성하기의 모든 레슨

직접 연습해 보세요: 온라인 Python 컴파일러