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์„ ์ง€ํ‚ด์œผ๋กœ์จ ๋ณ€๊ฒฝ์„ ์ตœ์†Œํ™”ํ•˜๋ฉด์„œ ํ™•์žฅ์„ ์‰ฝ๊ฒŒ ํ•  ์ˆ˜ ์žˆ๋‹ค.
  • ์—ฌ๋Ÿฌ๋ถ„๋“ค์˜ ๋…ธ๋ ฅ๊ณผ ์‹œ๊ฐ„์„ ์ ˆ์•ฝํ•ด์ค„ ์•„์ฃผ ๋ฉ‹์ง„ ์ „๋žต์ด๋ผ๋Š” ๊ฒƒ.

๋ฌด์—‡์ด ๋ณ€ํ•˜๋Š” ๊ฒƒ์ธ์ง€. ๋ฌด์—‡์ด ๋ณ€ํ•˜์ง€ ์•Š๋Š” ๊ฒƒ์ธ์ง€ ๊ตฌ๋ณ„ํ•˜์ž.

Reference