SOLID 디자인 원칙 - 단일 책임 원칙(Single Responsibility Priciple, SRP)

박남호·2022년 10월 21일
0
struct Journal
{
	string title;
    vector<string> entries;
  
	explicit Journal(const string& title) : title {title}{}
}
void Journal::add(const string& entry)
{
	static int count = 1;
    entries.push_back(boost::lexical_cast<string>(count++) + " : "+ entry);
}
Journal j{"Dear Diary"};
j.add("I cried today");
j.add("I ate a bug");

위 코드는 메모장의 기능을 구현한 것이다.

void Journal::save(const string& filename)
{
	ofstream ofs(filename);
    for(auto& s : entries)
    	ofs << s <<endl;
}

보통 이렇게 save 함수까지 추가해서 사용하지만 이러한 방식에는 문제가 있다.
메모장의 책임은 메모 항목들을 기입/관리하는 것이지 디스크에 쓰는게 아니기 때문이다.
이런 경우 파일 저장 기능은 별도의 클래스로 만드는 것이 바람직 하다.

struct PersistenceManager
{
	struct void save(const Juarnals& j, const string& filename)
    {
    	ofstream ofs(filename);
        for(auto& s : j.entries)
        	ofs << s << endl;
    }
};

단일 책임 원칙이 의미하는 바가 이런 것이다. 각 클래스는 단 한 가지의 책임을 부여받고 수정할 이유가 단 한가지여야 한다. 즉 메모 기능에 대해 수정할 때만 Journal 클래스를 수정을 해야한다. Save와 같은 기능은 메모 기능이 아니기 때문에 따로 클래스를 생성해야 한다. 하나의 클래스에 여러가지 기능을 구현하는 것은 바람직하지 못하다.

profile
NamoPark

0개의 댓글