OCP(Open Closed Principle)
๊ธฐ์กด์ ์ฝ๋๋ฅผ ๋ณ๊ฒฝํ์ง ์์ผ๋ฉด์ ๊ธฐ๋ฅ์ ์ถ๊ฐํ ์ ์๋๋ก ์ค๊ณ๊ฐ ๋์ด์ผ ํ๋ค.
Example
์์ ๊ทธ๋ฆผ์ฒ๋ผ User
๋ Logic
์ ์ง์ ์ ์ผ๋ก ์ฐธ์กฐํ๊ณ ๊ฐ์ ํด๋ณด์.
์ฐ๋ฆฌ๋ ์๋ก์ด ๋ ๋ฒ์งธ์ Logic
์ ๊ตฌํํ์ฌ User
์ ์ ์ฉ์ ํด์ผ ํ๋ค. ๊ธฐ์กด์ User
๋ ์ฒซ ๋ฒ์งธ Logic
์ ์ง์ ์ ์ผ๋ก ์ฐธ์กฐํ๊ณ ์๊ธฐ ๋๋ฌธ์ User
์ ์ง์ ์ ์ธ ๋ณํ๊ฐ ํ์ํ๋ค.
์์ ๊ฐ์ด ์๋ก์ด Logic
์ ์ถ๊ฐํ ๋๋ง๋ค ๋ณ๊ฒฝ์ ์ต์ํ ํ์ง ์๋๋ค๋ฉด recompile๊ณผ redeploy๋ฅผ ๋ค์ ๊ฑฐ์ณ์ผ ํ๋ ๋น์ฉ์ด ๋ ๋ค.
์ด๋ฌํ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด์๋ OCP(Open Closed Principle) ๊ท์น์ ์ ์ฉํ๋ฉด ๋๋ค.
์ฐ๋ฆฌ๋ File
๊ณผ ์งํ์ํ๋ฅผ ๋ณผ ์ ์๋ Progress
ํด๋์ค 2๊ฐ๊ฐ ์๋ค.
class File {
public $length;
public $sent;
}
class Progress {
private $file;
function __construct(File $file) {
$this->file = $file;
}
function getAsPercent() {
return $this->file->sent * 100 / $this->file->length;
}
}
์คํํ๋ฉด์ ์๋์ ๊ฐ๋ค.
Testing started at 5:39 PM ...
PHPUnit 3.7.28 by Sebastian Bergmann.
.
Time: 15 ms, Memory: 2.50Mb
OK (1 test, 1 assertion)
ํ์ง๋ง ์ฌ๊ธฐ์ File
๋ง๊ณ ๋ค๋ฅธ ํ์ผ์ข
๋ฅ(Music
)๊ฐ ์ถ๊ฐ๊ฐ ๋๋ฉด ์ด๋ป๊ฒ ํด์ผํ ๊น..?
class Music {
public $length;
public $sent;
public $artist;
public $album;
public $releaseDate;
function getAlbumCoverFile() {
return 'Images/Covers/' . $this->artist . '/' . $this->album . '.png';
}
}
๊ธฐ์กด์ Progress
ํด๋์ค๋ File
์ ์ฐธ์กฐํ๊ณ ์๊ธฐ ๋๋ฌธ์ ๋ค๋ฅธ ํด๋์ค๋ก ํ์ฅํ๊ธฐ ํ๋ ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง๊ณ ์๋ค.
๋ฐ๋ผ์ File
์ ์ข
๋ฅ๋ฅผ ํ๋์ ์ธํฐํ์ด์ค์ธ Measurable
๋ก ์์ ํ์ฌ ํ์ฅํ๊ธฐ ์ฌ์ด ๊ตฌ์กฐ๋ก ๋ณ๊ฒฝ ํ ์ ์๋ค. ์๋ก์ด File
ํํ๋ ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํ์ฌ ์ฝ๊ฒ ์ถ๊ฐํ ์ ์๋ค. ๋ํ ๊ธฐ์กด์ Progress
๋ ๋ณ๊ฒฝ์ ํ์ง ์์๋ ๋๋ ์ฅ์ ์ด ์๋ค.
์๋๋ ์ค์ ์ ์ฉํ ์ฝ๋์ ๋๋ค.
interface Measurable {
function getLength();
function getSent();
}
class File implements Measurable {
private $length;
private $sent;
.....
}
class Progress {
private $measurableContent;
function __construct(Measurable $measurableContent) {
$this->measurableContent = $measurableContent;
}
function getAsPercent() {
return $this->measurableContent->getSent() * 100 / $this->measurableContent->getLength();
}
}
๊ฒฐ๋ก
OCP
์ ์งํด์ผ๋ก์จ ๋ณ๊ฒฝ์ ์ต์ํํ๋ฉด์ ํ์ฅ์ ์ฝ๊ฒ ํ ์ ์๋ค.- ์ฌ๋ฌ๋ถ๋ค์ ๋ ธ๋ ฅ๊ณผ ์๊ฐ์ ์ ์ฝํด์ค ์์ฃผ ๋ฉ์ง ์ ๋ต์ด๋ผ๋ ๊ฒ.
๋ฌด์์ด ๋ณํ๋ ๊ฒ์ธ์ง. ๋ฌด์์ด ๋ณํ์ง ์๋ ๊ฒ์ธ์ง ๊ตฌ๋ณํ์.