SRP(Single Responsibility Principle)
A class should have only one reason to change. // ํด๋์ค๊ฐ ๋ณ๊ฒฝ๋ ์ด์ ๋ ๋จ ํ๋์ฌ์ผ ํ๋ค.
Example
์๋์ Book
์ด๋ผ๋ ํด๋์ค๋ ๋งค์ฐ ๋
ผ๋ฆฌ์ ์ด๊ณ ๊ฐ๋จํ ํด๋์ค์ฒ๋ผ ๋ณด์
๋๋ค. ํด๋์ค๋ฅผ ํตํด ์ ๋ชฉ์ ์ป์ ์๋ ์๊ณ , ์๊ฐ, ๋ค์ํ์ด์ง, ํ์ฌ ํ์ด์ง ๋ด์ฉ์ ์ป์ ์ ์์ต๋๋ค.
class Book {
function getTitle() {
return "A Great Book";
}
function getAuthor() {
return "John Doe";
}
function turnPage() {
// pointer to next page
}
function printCurrentPage() {
echo "current page content";
}
}
ํ์ง๋ง ์์ ๋ฌธ์ ๊ฐ ์์ต๋๋ค. ์ฐ๋ฆฌ๊ฐ ์ฝ๊ฒ ์๊ฐํด๋ณด์์๋ Book
ํด๋์ค๋ฅผ ๋ค๋ฃจ๋ ํ์์๊ฐ ์ฑ
์ ๊ด๋ฆฌํ๋ ์ฌ๋์ด๊ฑฐ๋, ์ฑ
์ ๋ณด์ฌ์ฃผ๋ ์ฌ๋ ๋ ๋ถ๋ฅ๋ก ๋๋ ์ ์์ต๋๋ค.
๋ ๋ถ๋ฅ์ ํ์์๊ฐ ์ํ๋ bussiness logic
์ด Book
ํด๋์ค์ ์์ฌ์์ต๋๋ค. ์ด๋ฐ ๊ฒฝ์ฐ๋ SRP
๋ฅผ ์๋ฐํ ๊ฒฝ์ฐ๋ผ๊ณ ๋ณผ ์ ์์ต๋๋ค.
class Book {
function getTitle() {
return "A Great Book";
}
function getAuthor() {
return "John Doe";
}
function turnPage() {
// pointer to next page
}
function getCurrentPage() {
return "current page content";
}
}
interface Printer {
function printPage($page);
}
class PlainTextPrinter implements Printer {
function printPage($page) {
echo $page;
}
}
class HtmlPrinter implements Printer {
function printPage($page) {
echo '<div style="single-page">' . $page . '</div>';
}
}
๋ ๊ฐ์ง์ bussiness logic
์ ๋ถ๋ฅํจ์ผ๋ก์จ design
์ ์ ์ฐ์ฑ์ ์ป์ ์ ์์ต๋๋ค.
์๋์ ๊ฒฝ์ฐ ์ ์ฅํ๋ ๊ธฐ๋ฅ์ด ์ถ๊ฐ๋ Book
์
๋๋ค.
class Book {
function getTitle() {
return "A Great Book";
}
function getAuthor() {
return "John Doe";
}
function turnPage() {
// pointer to next page
}
function getCurrentPage() {
return "current page content";
}
function save() {
$filename = '/documents/'. $this->getTitle(). ' - ' . $this->getAuthor();
file_put_contents($filename, serialize($this));
}
}
์ฐ๋ฆฌ๊ฐ ์ ์ฅํ๋ ๋ฐฉ๋ฒ์ ๋ฐ๊ฟ๋ Book
ํด๋์ค๋ฅผ ๋ฐ๊ฟ์ผ ํฉ๋๋ค. ๋ํ ์ฐ๋ฆฌ๊ฐ ๋ค์ ํ์ด์ง๋ฅผ ๋๊ธฐ๋ ๊ณผ์ ์ ๋ฐ๊ฟ๋ Book
ํด๋์ค๋ฅผ ๋ฐ๊ฟ์ผ ํฉ๋๋ค. ์ด ํด๋์ค๋ฅผ ๋ฐ๊ฟ์ผํ๋ ์ด์ ๋ ์ฌ๋ฌ๊ฐ์ง์ ๋ณ๊ฒฝ์ ์ถ์ด ์กด์ฌํฉ๋๋ค.
save
๋ฅผ SimpleFilePersistence
ํด๋์ค๋ก ๋ถ๋ฆฌ์์ผ ๊ฐ ํด๋์ค๊ฐ ๋ณ๊ฒฝ๋ ์ด์ ๋ฅผ ์ต์ํํฉ๋๋ค.
class Book {
function getTitle() {
return "A Great Book";
}
function getAuthor() {
return "John Doe";
}
function turnPage() {
// pointer to next page
}
function getCurrentPage() {
return "current page content";
}
}
class SimpleFilePersistence {
function save(Book $book) {
$filename = '/documents/' . $book->getTitle() . ' - ' . $book->getAuthor();
file_put_contents($filename, serialize($book));
}
}
๊ฒฐ๋ก
SRP
์ ์งํด์ผ๋ก์จlow coupled design
์ ์ป์ ์ ์๋ค.- ํ์ง๋ง ๊ณผ๋ํ
SRP
๋ ์ต์ ํ ๋์์ธ ๋์ ๋ฏธ์์ฑ๋ ์ต์ ํ ๋์์ธ์ผ๋ก ์ด๋ ์ ์๋ค. - ๋ํ ๋ถ์ฐ๋ ์์
class
๋ก ์ธํด ์ดํดํ๊ธฐ ํ๋ ๋์์ธ์ด ๋ ์ ์๋ค.