<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jirayu Photisan on Medium]]></title>
        <description><![CDATA[Stories by Jirayu Photisan on Medium]]></description>
        <link>https://medium.com/@gdunghi?source=rss-4570570b2ddb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xmWeOZU7KXEAv5u0ttm1uw.jpeg</url>
            <title>Stories by Jirayu Photisan on Medium</title>
            <link>https://medium.com/@gdunghi?source=rss-4570570b2ddb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 08:44:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gdunghi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Applying Algebraic Data Types in Domain-Driven Design]]></title>
            <link>https://medium.com/@gdunghi/applying-algebraic-data-types-in-domain-driven-design-974cc2dafa25?source=rss-4570570b2ddb------2</link>
            <guid isPermaLink="false">https://medium.com/p/974cc2dafa25</guid>
            <dc:creator><![CDATA[Jirayu Photisan]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 15:02:18 GMT</pubDate>
            <atom:updated>2026-10-11T15:13:52.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3WvPNH49Gzj6t5zgUnm2cg.png" /></figure><p>การนำ Algebraic Data Types (ADTs) มาประยุกต์ใช้ใน Domain-Driven Design (DDD) มีแก่นสำคัญอยู่ที่แนวคิด “Make Illegal States Unrepresentable” หรือการทำให้ระบบไม่สามารถจำลองสถานะที่ผิดไปจาก Business Logic ได้ตั้งแต่ขั้นตอนการคอมไพล์</p><p>ในอดีตเรามักออกแบบ Entity ให้มีฟิลด์ทุกอย่างครอบจักรวาล และใช้ null หรือ status flag เพื่อบอกว่าตอนนี้ออบเจกต์อยู่ในสถานะไหน ซึ่งนำไปสู่การเช็ค if (status == ...) และ null check ที่ซ้ำซ้อนทั่วทั้งโปรแกรม ADTs จะเข้ามาแก้ปัญหานี้ด้วยการแยกสถานะทางธุรกิจออกเป็น Type ที่ชัดเจน</p><h3>ตัวอย่าง: ระบบจัดการคำสั่งซื้อ (Order Lifecycle)</h3><p>สมมติว่าเรามี Business Rule ของการสั่งซื้อดังนี้:</p><ol><li><strong>Draft:</strong> คำสั่งซื้อที่ยังไม่ชำระเงิน (ต้องมีรายการสินค้า)</li><li><strong>Paid:</strong> คำสั่งซื้อที่ชำระเงินแล้ว (ต้องมีรหัสการชำระเงิน)</li><li><strong>Shipped:</strong> คำสั่งซื้อที่จัดส่งแล้ว (ต้องมีหมายเลขพัสดุ)</li><li><strong>Cancelled:</strong> คำสั่งซื้อที่ถูกยกเลิก (ต้องระบุเหตุผล)</li></ol><h3>การออกแบบแบบดั้งเดิม (Anemic Domain Model)</h3><p>โครงสร้างแบบนี้ทำให้เกิด “สถานะที่ผิดกฎ” ได้ เช่น คำสั่งซื้อมีสถานะเป็น DRAFT แต่ดันมี trackingNumber ปรากฏอยู่</p><pre>data class Order(<br>    val id: String,<br>    val items: List&lt;String&gt;,<br>    var status: String, // &quot;DRAFT&quot;, &quot;PAID&quot;, &quot;SHIPPED&quot;, &quot;CANCELLED&quot;<br>    var paymentId: String?, // อาจจะ null ถ้ายังไม่จ่าย<br>    var trackingNumber: String?, // อาจจะ null ถ้ายังไม่ส่ง<br>    var cancelReason: String? // อาจจะ null ถ้าไม่ได้ยกเลิก<br>)</pre><h3>การประยุกต์ใช้ ADTs ใน DDD (Kotlin)</h3><p>เราจะใช้ <strong>Sum Types</strong> (sealed interface) เพื่อกำหนดสถานะทั้งหมดที่เป็นไปได้ และใช้ <strong>Product Types</strong> (data class) เพื่อกำหนดว่าในแต่ละสถานะนั้น &quot;ต้องมี&quot; ข้อมูลอะไรบ้าง</p><pre>sealed interface Order {<br>    val id: String // ทุกสถานะต้องมี ID<br>    data class Draft(<br>        override val id: String,<br>        val items: List&lt;String&gt;<br>    ) : Order<br>    data class Paid(<br>        override val id: String,<br>        val items: List&lt;String&gt;,<br>        val paymentId: String // บังคับว่าถ้า Paid ต้องมีสิ่งนี้ (ห้าม null)<br>    ) : Order<br>    data class Shipped(<br>        override val id: String,<br>        val items: List&lt;String&gt;,<br>        val paymentId: String,<br>        val trackingNumber: String // บังคับว่าถ้า Shipped ต้องมีสิ่งนี้ (ห้าม null)<br>    ) : Order<br>    data class Cancelled(<br>        override val id: String,<br>        val reason: String // บังคับว่าถ้ายกเลิกต้องมีเหตุผล<br>    ) : Order<br>}</pre><h3>การจัดการ Business Logic ด้วย ADTs</h3><p>เมื่อเราออกแบบ Domain Model ด้วย ADTs การจัดการ State Transition (การเปลี่ยนสถานะ) จะปลอดภัยและสะท้อน Business Flow ได้อย่างสมบูรณ์แบบ</p><h4>1. บังคับ Input ของ Behavior ด้วย Type</h4><p>ฟังก์ชันทางธุรกิจจะไม่รับ Order แบบกว้างๆ อีกต่อไป แต่จะรับเฉพาะสถานะที่อนุญาตให้ทำ Action นั้นได้เท่านั้น</p><pre>// การจ่ายเงิน จะรับเฉพาะ Order ที่เป็น Draft เท่านั้น!<br>// (ถ้าส่ง Order.Paid หรือ Order.Shipped เข้ามา คอมไพล์จะไม่ผ่านทันที)<br>fun payOrder(order: Order.Draft, paymentId: String): Order.Paid {<br>    // ไม่มีทางที่ order จะมี status ผิดพลาดได้<br>    return Order.Paid(<br>        id = order.id,<br>        items = order.items,<br>        paymentId = paymentId<br>    )<br>}</pre><pre>// การจัดส่ง จะรับเฉพาะ Order ที่จ่ายเงินแล้ว (Paid) เท่านั้น!<br>fun shipOrder(order: Order.Paid, trackingNumber: String): Order.Shipped {<br>    return Order.Shipped(<br>        id = order.id,<br>        items = order.items,<br>        paymentId = order.paymentId,<br>        trackingNumber = trackingNumber<br>    )<br>}</pre><h4>2. การตัดสินใจด้วย Exhaustive Pattern Matching</h4><p>เมื่อ Business Use Case ต้องการดึงข้อมูลหรือประมวลผลตามสถานะของ Order เราสามารถใช้ when เพื่อบังคับให้ Handle ครบทุกเคส</p><pre>fun processOrderEvent(order: Order) {<br>    // คอมไพเลอร์บังคับให้เช็คครบทั้ง 4 สถานะ หากตกหล่นหรือมีการเพิ่มสถานะใหม่ในอนาคต จะ Error ทันที<br>    when (order) {<br>        is Order.Draft -&gt; println(&quot;Waiting for payment on order ${order.id}&quot;)<br>        is Order.Paid -&gt; println(&quot;Preparing to ship. Payment ID: ${order.paymentId}&quot;)<br>        is Order.Shipped -&gt; println(&quot;Order shipped! Track here: ${order.trackingNumber}&quot;)<br>        is Order.Cancelled -&gt; println(&quot;Order cancelled due to: ${order.reason}&quot;)<br>    }<br>}</pre><h3>สรุปประโยชน์ที่ได้รับในมุมมอง DDD</h3><ul><li><strong>Domain Model เป็นเอกสารในตัว:</strong> โค้ดสื่อสาร Business Logic ได้ทันทีโดยไม่ต้องอ่าน Document (รู้เลยว่า Paid ต้องมี PaymentId)</li><li><strong>ลด Defensive Programming:</strong> ไม่ต้องเขียน if (order.status == &quot;PAID&quot; &amp;&amp; order.paymentId != null) กระจายอยู่ทั่วโปรเจกต์</li><li><strong>Push Errors to Compile Time:</strong> ป้องกันการเรียกใช้ Business Logic ผิดจังหวะ (เช่น พยายาม Ship สินค้าที่ยังไม่จ่ายเงิน) ตั้งแต่ตอนที่โปรแกรมเมอร์พิมพ์โค้ด</li></ul><p>หากในอนาคตมี Requirement ใหม่เพิ่มสถานะ <strong>“Refunded”</strong> ทันทีที่เราเพิ่ม data class Refunded เข้าไปใน sealed interface ตัว Compiler จะชี้เป้าทันทีว่ามีจุดไหนบ้างในโค้ดเบสที่เราลืมเขียน Handle สถานะใหม่นี้</p><p>การนำ Algebraic Data Types มาใช้ควบคู่กับ Domain-Driven Design ไม่ใช่แค่เรื่องของเทคนิคการเขียนโค้ด แต่เป็นการเปลี่ยนมุมมองให้ “โค้ด” สะท้อน “ภาษาทางธุรกิจ” (Ubiquitous Language) ได้อย่างแท้จริง มันช่วยลดภาระในการอ่าน Document ลดการเขียนเทสต์สำหรับเคสที่เป็นไปไม่ได้ และเปลี่ยนบั๊กที่ควรจะไประเบิดตอน Runtime ให้จบลงตั้งแต่ Compile time</p><p><em>Happy coding</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=974cc2dafa25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interface Segregation Principle (ISP)]]></title>
            <link>https://medium.com/@gdunghi/interface-segregation-principle-isp-1876c6388962?source=rss-4570570b2ddb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1876c6388962</guid>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[isp]]></category>
            <dc:creator><![CDATA[Jirayu Photisan]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 03:40:21 GMT</pubDate>
            <atom:updated>2026-08-25T02:29:58.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0Bs8cGyJ3R_1ouao_sCrA.png" /></figure><p><strong>Interface Segregation Principle</strong> เป็นหลักข้อที่ 4 ของ <strong>SOLID</strong></p><p><strong>“Clients should not be forced to depend on methods they do not use.”</strong><br> ผู้ที่ใช้งาน Interface ไม่ควรถูกบังคับให้ต้องพึ่งพา method ที่ตัวเองไม่ได้ใช้</p><p>พูดง่าย ๆ คือ:</p><blockquote>อย่าสร้าง Interface ใหญ่เกินไปจนคนที่ implement ต้องเอา method ที่ไม่เกี่ยวข้องมาทำด้วย</blockquote><h3>ตัวอย่างที่ไม่ Follow ISP</h3><p>สมมติเรามีระบบจัดการพนักงาน:</p><pre>interface Employee {<br>    void work();<br>    void eat();<br>    void sleep();<br>}</pre><p>แล้วมี HumanEmployee</p><pre>class HumanEmployee implements Employee {<br><br>    @Override<br>    public void work() {<br>        System.out.println(&quot;Working...&quot;);<br>    }<br><br>    @Override<br>    public void eat() {<br>        System.out.println(&quot;Eating...&quot;);<br>    }<br><br>    @Override<br>    public void sleep() {<br>        System.out.println(&quot;Sleeping...&quot;);<br>    }<br>}</pre><p>ดูเหมือนจะไม่มีปัญหา</p><p>แต่ถ้าเพิ่ม Robot:</p><pre>class RobotEmployee implements Employee {<br><br>    @Override<br>    public void work() {<br>        System.out.println(&quot;Working...&quot;);<br>    }<br><br>    @Override<br>    public void eat() {<br>        // Robot doesn&#39;t eat<br>        throw new UnsupportedOperationException();<br>    }<br><br>    @Override<br>    public void sleep() {<br>        // Robot doesn&#39;t sleep<br>        throw new UnsupportedOperationException();<br>    }<br>}</pre><p>ตรงนี้เริ่มมีปัญหาแล้ว</p><p>RobotEmployee <strong>ไม่ได้ต้องการ </strong><strong>eat() และ </strong><strong>sleep()</strong></p><p>แต่ Interface บังคับให้ต้อง implement</p><p>นี่คือการ <strong>ละเมิด ISP</strong></p><h3>แก้ด้วย Interface Segregation</h3><p>แยก Interface ใหญ่เป็น Interface เล็ก ๆ</p><pre>interface Workable {<br>    void work();<br>}<br><br>interface Eatable {<br>    void eat();<br>}<br><br>interface Sleepable {<br>    void sleep();<br>}</pre><p>Human:</p><pre>class HumanEmployee implements Workable, Eatable, Sleepable {<br><br>    public void work() {<br>        System.out.println(&quot;Working...&quot;);<br>    }<br><br>    public void eat() {<br>        System.out.println(&quot;Eating...&quot;);<br>    }<br><br>    public void sleep() {<br>        System.out.println(&quot;Sleeping...&quot;);<br>    }<br>}</pre><pre>class RobotEmployee implements Workable {<br><br>    public void work() {<br>        System.out.println(&quot;Working...&quot;);<br>    }<br>}</pre><p>แบบนี้ RobotEmployee ไม่ต้องรู้จัก eat() หรือ sleep() เลย</p><h3>แล้ว ISP ต่างจากการ “แบ่ง Interface” ธรรมดายังไง?</h3><p>หัวใจสำคัญคือ <strong>แบ่งตาม Client ที่ใช้งาน</strong></p><p>สมมติเรามี:</p><pre>interface UserService {<br><br>    User createUser();<br><br>    User getUser();<br><br>    void updateUser();<br><br>    void deleteUser();<br><br>    List&lt;User&gt; searchUser();<br><br>    void resetPassword();<br><br>    void sendEmail();<br><br>    void exportExcel();<br><br>}</pre><p>Interface นี้เริ่มใหญ่เกินไป</p><p>สมมติหน้าจอ User List ใช้แค่:</p><pre>getUser()<br>searchUser()</pre><p>แต่ Controller ต้อง depend กับ UserService ทั้งก้อน</p><pre>class UserController {<br><br>    private final UserService userService;<br><br>}</pre><p>แปลว่า Controller นี้ <strong>ถูกผูกกับความสามารถทั้งหมดของ UserService</strong> แม้จะใช้แค่ 2 method</p><p>สิ่งที่ควรจะเป็นคือ</p><h3>แยกตาม Client</h3><p>เราอาจออกแบบเป็น:</p><pre>interface UserReader {<br>    User getUser();<br>    List&lt;User&gt; searchUser();<br>}</pre><pre>interface UserWriter {<br>    User createUser();<br>    void updateUser();<br>    void deleteUser();<br>}</pre><pre>interface UserPasswordManager {<br>    void resetPassword();<br>}</pre><pre>interface UserExporter {<br>    void exportExcel();<br>}</pre><p>จากนั้น:</p><pre>class UserController {<br><br>    private final UserReader userReader;<br><br>}</pre><p>Controller สนใจเฉพาะสิ่งที่ตัวเองต้องใช้</p><p>สรุป:</p><p>ใน Clean Architecture มีแนวคิดที่เข้ากันโดยตรงคือ</p><p><strong><em>Dependency ควรชี้ไปหา abstraction ที่ consumer ต้องการจริง ๆ</em></strong></p><pre>Controller<br>    │<br>    ▼<br>UserReader<br>    │<br>    ▼<br>UserService</pre><p>แทนที่จะ:</p><pre>Controller<br>    │<br>    ▼<br>HugeUserService<br>    │<br>    ├── create<br>    ├── update<br>    ├── delete<br>    ├── search<br>    ├── export<br>    ├── resetPassword<br>    ├── sendEmail<br>    └── ...</pre><p>ISP ไม่ได้แปลว่า Interface ต้องเล็กที่สุด ISP ไม่ได้บอกว่า ทุก Interface ต้องมีแค่ 1 method นั่นจะกลายเป็นการทำ Interface เล็กเกินไปจนระบบยุ่งเหยิง</p><p>ถึงตรงนี้แล้วไปต่อกันเลยที่หัวข้อถัดไป <a href="https://medium.com/@gdunghi/dependency-inversion-principle-dip-c1df5c344592">Dependency Inversion Principle (DIP)</a></p><blockquote>Happy coding<br><strong>หมายเหตุ:</strong> บทความนี้เรียบเรียงและปรับภาษาโดยใช้ ChatGPT ช่วย โดยเนื้อหา แนวคิด และตัวอย่างมาจากผู้เขียน</blockquote><h3>SOLID Principles</h3><ul><li><a href="https://medium.com/@gdunghi/single-responsibility-principle-srp-solid-principle-b8d9e9962ab4">Single Responsibility Principle (SRP)</a></li><li><a href="https://medium.com/@gdunghi/open-closed-principle-ocp-%E0%B9%80%E0%B8%82%E0%B8%B5%E0%B8%A2%E0%B8%99-code-%E0%B8%A2%E0%B8%B1%E0%B8%87%E0%B9%84%E0%B8%87%E0%B9%83%E0%B8%AB%E0%B9%89%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B1%E0%B8%9A%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%80%E0%B8%9B%E0%B8%A5%E0%B8%B5%E0%B9%88%E0%B8%A2%E0%B8%99%E0%B9%81%E0%B8%9B%E0%B8%A5%E0%B8%87-ed66d0bc0574">Open/Closed Principle (OCP)</a></li><li><a href="https://medium.com/@gdunghi/liskov-substitution-principle-lsp-%E0%B9%80%E0%B8%A1%E0%B8%B7%E0%B9%88%E0%B8%AD-subclass-%E0%B8%84%E0%B8%A7%E0%B8%A3%E0%B9%81%E0%B8%97%E0%B8%99%E0%B8%97%E0%B8%B5%E0%B9%88-parent-%E0%B9%84%E0%B8%94%E0%B9%89%E0%B8%88%E0%B8%A3%E0%B8%B4%E0%B8%87-c7a9b508f850">Liskov Substitution Principle (LSP)</a></li><li><a href="https://medium.com/@gdunghi/interface-segregation-principle-isp-1876c6388962">Interface Segregation Principle (ISP)</a></li><li><a href="https://medium.com/@gdunghi/dependency-inversion-principle-dip-c1df5c344592">Dependency Inversion Principle (DIP)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1876c6388962" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Inversion Principle (DIP)]]></title>
            <link>https://medium.com/@gdunghi/dependency-inversion-principle-dip-c1df5c344592?source=rss-4570570b2ddb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1df5c344592</guid>
            <dc:creator><![CDATA[Jirayu Photisan]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 11:49:47 GMT</pubDate>
            <atom:updated>2026-08-12T06:35:40.252Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dependency Inversion Principle (DIP): หลักการที่ทำให้ Code ไม่ผูกติดกับ Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/0*uQOCA2vZRTSOrYUK.png" /><figcaption><a href="https://blog.ndepend.com/wp-content/uploads/SOLID-Principle-Dependency-Inversion-Principle.png">https://blog.ndepend.com/wp-content/uploads/SOLID-Principle-Dependency-Inversion-Principle.png</a></figcaption></figure><h3>Dependency Inversion Principle (DIP): หลักการที่ทำให้ Code ไม่ผูกติดกับ Implementation</h3><p>จาก <strong>SOLID Principles</strong></p><pre>S = Single Responsibility<br>    หนึ่ง class มีหนึ่ง responsibility<br><br>O = Open/Closed<br>    เพิ่มความสามารถโดยไม่ต้องแก้ของเดิม<br><br>L = Liskov Substitution<br>    ลูกต้องแทนพ่อได้โดยไม่ทำให้ระบบพัง<br><br>I = Interface Segregation<br>    อย่าบังคับให้ client depend กับสิ่งที่ไม่ใช้<br><br>D = Dependency Inversion<br>    พึ่ง abstraction ไม่พึ่ง implementation</pre><p>แต่ถ้าจะลงรายละเอียดจริง ๆ แล้ว <strong>Dependency Inversion Principle (DIP)</strong> มีความหมายลึกกว่านั้นมาก</p><p>DIP ไม่ได้บอกเพียงว่า</p><blockquote><em>ใช้ Interface</em></blockquote><p>แต่กำลังบอกว่า</p><blockquote><strong><em>High-level policy ไม่ควรขึ้นอยู่กับ Low-level implementation ทั้งสองควรขึ้นอยู่กับ Abstraction</em></strong></blockquote><p>และ</p><blockquote><strong><em>Abstraction ไม่ควรขึ้นอยู่กับรายละเอียด แต่รายละเอียดควรขึ้นอยู่กับ Abstraction</em></strong></blockquote><p>หลักการนี้เป็นหนึ่งในแนวคิดสำคัญที่อยู่เบื้องหลัง <strong>Clean Architecture, Hexagonal Architecture และ Ports &amp; Adapters</strong></p><h3>ปัญหาของ Code ที่ Dependency ผูกกันแน่น</h3><p>ลองดูตัวอย่างง่าย ๆ</p><p>เรามีระบบสั่งซื้อสินค้า</p><pre>class OrderService {<br>    private final MySQLOrderRepository repository;<br>    public OrderService() {<br>        this.repository = new MySQLOrderRepository();<br>    }<br>    public void createOrder(Order order) {<br>        repository.save(order);<br>    }<br>}</pre><p>ตอนแรกดูเหมือนจะไม่มีปัญหา</p><p>OrderService ต้องการเก็บ Order ลง Database และเราใช้ MySQL ดังนั้นก็สร้าง MySQLOrderRepository ขึ้นมา</p><p>แต่ลองคิดต่อว่าในอนาคตเราอยากเปลี่ยนจาก MySQL เป็น PostgreSQL</p><p>หรืออยากใช้ MongoDB</p><p>หรืออยาก Mock Repository ตอน Unit Test</p><p>เราจะพบว่า OrderService ถูกผูกติดกับ MySQLOrderRepository โดยตรง</p><pre>OrderService<br>     |<br>     | depends on<br>     v<br>MySQLOrderRepository<br>     |<br>     v<br>   MySQL</pre><p>ปัญหาคือ <strong>Business Logic ของเราไม่ควรต้องรู้ว่า Database ที่ใช้คืออะไร</strong></p><h3>High-Level กับ Low-Level คืออะไร?</h3><p>ก่อนเข้าใจ DIP ต้องแยกสองคำนี้ก่อน</p><h3>High-Level Module</h3><p>คือส่วนที่มี <strong>Business Rule / Business Policy</strong></p><p>ตัวอย่าง:</p><pre>OrderService<br>PaymentService<br>UserService<br>TransferMoneyUseCase<br>CreateOrderUseCase</pre><p>สิ่งเหล่านี้บอกว่า</p><blockquote><em>“ระบบต้องทำอะไร”</em></blockquote><p>เช่น</p><pre>orderService.createOrder();</pre><p>หรือ</p><pre>transferMoneyUseCase.execute();</pre><h3>Low-Level Module</h3><p>คือรายละเอียดทางเทคนิคที่ใช้ทำให้ Business Logic ทำงาน</p><p>เช่น</p><pre>MySQLOrderRepository<br>PostgresOrderRepository<br>RedisCache<br>KafkaMessagePublisher<br>SMTPEmailSender<br>S3FileStorage</pre><p>สิ่งเหล่านี้บอกว่า</p><blockquote><em>“ทำอย่างไร”</em></blockquote><p>ดังนั้นเราสามารถมองภาพได้ว่า</p><pre>Business Rule<br>     |<br>     v<br>OrderService<br>     |<br>     v<br>   MySQL</pre><p>ปัญหาคือ Business Rule กำลังขึ้นอยู่กับรายละเอียดทางเทคนิค</p><h3>DIP ต้องการให้ Dependency กลับทิศ</h3><p>แทนที่จะเป็น</p><pre>High-Level<br>    |<br>    v<br>Low-Level</pre><p>เราต้องการให้ทั้งสองฝั่งขึ้นอยู่กับ Abstraction</p><pre>Abstraction<br>             &lt;&lt;interface&gt;&gt;<br>                  ^<br>                  |<br>        +---------+---------+<br>        |                   |<br>        |                   |<br>High-Level             Low-Level<br>OrderService       MySQLOrderRepository</pre><p>หรือพูดง่าย ๆ ว่า</p><pre>OrderService<br>     |<br>     v<br>OrderRepository<br>     ^<br>     |<br>MySQLOrderRepository</pre><p>OrderService ไม่รู้จัก MySQLOrderRepository</p><p>มันรู้จักเพียง</p><pre>OrderRepository</pre><h3>เริ่มจาก Interface</h3><p>เราสร้าง Abstraction ขึ้นมาก่อน</p><pre>public interface OrderRepository {<br>    void save(Order order);<br>    Order findById(Long id);<br>}</pre><p>จากนั้น OrderService จะ Depend กับ Interface</p><pre>public class OrderService {<br>    private final OrderRepository repository;<br>    public OrderService(OrderRepository repository) {<br>        this.repository = repository;<br>    }<br>    public void createOrder(Order order) {<br>        repository.save(order);<br>    }<br>}</pre><p>ตอนนี้ OrderService ไม่รู้แล้วว่า Repository ใช้ Database อะไร</p><p>มันรู้เพียงว่า</p><blockquote><em>“ถ้าฉันเรียก </em><em>save() ต้องสามารถบันทึก Order ได้&quot;</em></blockquote><h3>Low-Level Implementation</h3><p>จากนั้นเราสามารถสร้าง Implementation</p><pre>public class MySQLOrderRepository implements OrderRepository {<br>   @Override<br>    public void save(Order order) {<br>        // Save to MySQL<br>    }<br>    @Override<br>    public Order findById(Long id) {<br>        // Query MySQL<br>        return null;<br>    }<br>}</pre><p>หรือถ้าเปลี่ยนเป็น PostgreSQL</p><pre>public class PostgreSQLOrderRepository implements OrderRepository {<br>    @Override<br>    public void save(Order order) {<br>        // Save to PostgreSQL<br>    }<br>    @Override<br>    public Order findById(Long id) {<br>        // Query PostgreSQL<br>        return null;<br>    }<br>}</pre><p>สิ่งสำคัญคือ</p><p><strong>เราไม่ต้องแก้ </strong><strong>OrderService</strong></p><p>เพราะ OrderService ไม่ได้ขึ้นอยู่กับ Implementation</p><h3>6. Dependency ถูก Invert อย่างไร?</h3><p>ลองเปรียบเทียบสองแบบ</p><h4>ก่อนใช้ DIP</h4><pre>OrderService<br>     |<br>     v<br>MySQLOrderRepository<br>     |<br>     v<br>   MySQL</pre><p>Business Logic → Database</p><p>ทำให้ Business Logic ผูกกับรายละเอียดทางเทคนิค</p><h4>หลังใช้ DIP</h4><pre>OrderRepository<br>               &lt;&lt;interface&gt;&gt;<br>                  ^       ^<br>                  |       |<br>                  |       |<br>          MySQLRepository  PostgreSQLRepository<br>                  ^<br>                  |<br>             OrderService<br></pre><p>ตอนนี้ทั้งสองฝั่งขึ้นอยู่กับ OrderRepository</p><pre>OrderService ----------&gt; OrderRepository<br>                              ^<br>                              |<br>                              |<br>                   MySQLOrderRepository</pre><p>นี่คือคำว่า <strong>Dependency Inversion</strong></p><p>Dependency ที่เคยชี้จาก High-Level → Low-Level ถูกเปลี่ยนให้ทั้งสองฝั่งพึ่งพา Abstraction</p><h3>แล้ว Dependency Injection เกี่ยวอะไรกับ DIP?</h3><p>สองอย่างนี้ไม่ใช่สิ่งเดียวกัน</p><p><strong>DIP = หลักการออกแบบ</strong></p><p><strong>Dependency Injection = เทคนิคที่ใช้ส่ง Dependency เข้าไป</strong></p><p>ตัวอย่าง:</p><pre>public class OrderService {<br>    private final OrderRepository repository;<br>    public OrderService(OrderRepository repository) {<br>        this.repository = repository;<br>    }<br>}</pre><p>ตรงนี้คือ Constructor Injection</p><p>จากนั้น Spring สามารถจัดการให้เราได้</p><pre>@Service<br>public class OrderService {<br>    private final OrderRepository repository;<br>    public OrderService(OrderRepository repository) {<br>        this.repository = repository;<br>    }<br>}</pre><p>และ</p><pre>@Repository<br>public class MySQLOrderRepository<br>        implements OrderRepository {<br>        // ...<br>}</pre><p>Spring จะทำประมาณนี้ให้เรา:</p><pre>MySQLOrderRepository<br>          |<br>          | implements<br>          v<br>OrderRepository<br>          ^<br>          |<br>          | inject<br>          |<br>    OrderService</pre><p>ดังนั้นจำง่าย ๆ:</p><blockquote><strong><em>DIP คือ Principle ส่วน DI คือ Technique</em></strong></blockquote><p>เราใช้ Dependency Injection เพื่อช่วยให้การออกแบบตาม DIP ทำได้ง่ายขึ้น</p><h3>DIP ทำให้ Unit Test ง่ายขึ้น</h3><p>นี่เป็นประโยชน์ที่เห็นได้ชัดมาก</p><p>ถ้า OrderService สร้าง MySQL Repository เอง</p><pre>class OrderService {<br>    private final MySQLOrderRepository repository;<br>    public OrderService() {<br>        repository = new MySQLOrderRepository();<br>    }<br>}</pre><p>เวลาทดสอบ เราอาจต้องใช้ Database จริง</p><p>ซึ่งทำให้ Unit Test กลายเป็น Integration Test ไปโดยไม่จำเป็น</p><p>แต่ถ้าใช้ DIP:</p><pre>class OrderService {<br>    private final OrderRepository repository;<br>    public OrderService(OrderRepository repository) {<br>        this.repository = repository;<br>    }<br>}</pre><p>เราสามารถสร้าง Fake หรือ Mock ได้</p><pre>OrderRepository repository = mock(OrderRepository.class);<br>OrderService service =<br>        new OrderService(repository);</pre><p>จากนั้นทดสอบ Business Logic ได้โดยไม่ต้องเปิด MySQL</p><pre>          Unit Test<br>              |<br>              v<br>        OrderService<br>              |<br>              v<br>       Mock OrderRepository<br>              |<br>              X<br>           Database</pre><p>นี่คือเหตุผลว่าทำไม DIP จึงช่วยให้ระบบ <strong>Testable</strong></p><h3>ตัวอย่างที่เห็นภาพมากขึ้น: Payment</h3><p>สมมติระบบของเรารองรับการชำระเงิน</p><p>เริ่มแรกเราเขียนแบบนี้</p><pre>class PaymentService {<br>    private final StripePayment payment;<br>    public PaymentService() {<br>        this.payment = new StripePayment();<br>    }<br>    public void pay(BigDecimal amount) {<br>        payment.charge(amount);<br>    }<br>}</pre><p>ปัญหาคือ Business Logic ผูกกับ Stripe</p><p>ถ้าวันหนึ่งต้องเพิ่ม</p><pre>Stripe<br>Omise<br>PayPal<br>2C2P<br>Bank Transfer</pre><p>PaymentService จะเริ่มยุ่ง</p><h3>ใช้ DIP แก้ปัญหา</h3><p>สร้าง Abstraction:</p><pre>public interface PaymentGateway {<br>   void charge(BigDecimal amount);<br>}</pre><p>Stripe:</p><pre>public class StripePaymentGateway<br>        implements PaymentGateway {<br>    @Override<br>    public void charge(BigDecimal amount) {<br>        // Stripe API<br>    }<br>}</pre><p>Omise:</p><pre>public class OmisePaymentGateway<br>        implements PaymentGateway {<br>@Override<br>    public void charge(BigDecimal amount) {<br>        // Omise API<br>    }<br>}</pre><p>Business Logic:</p><pre>public class PaymentService {<br>    private final PaymentGateway paymentGateway;<br>    public PaymentService(<br>            PaymentGateway paymentGateway) {<br>        this.paymentGateway = paymentGateway;<br>    }<br>    public void pay(BigDecimal amount) {<br>        paymentGateway.charge(amount);<br>    }<br>}</pre><p>ตอนนี้</p><pre>                 PaymentGateway<br>                 &lt;&lt;interface&gt;&gt;<br>                  /          \<br>                 /            \<br>                v              v<br>       StripeGateway      OmiseGateway<br>                ^<br>                |<br>                |<br>         PaymentService</pre><p>PaymentService ไม่สนใจว่า Payment Provider คือใคร</p><p>มันสนใจแค่ว่า</p><pre>paymentGateway.charge(amount);</pre><p>สามารถทำงานได้</p><h3>ตัวอย่าง Spring Boot ที่ใช้งานจริง</h3><p>สมมติเรามี Use Case:</p><pre>public class CreateOrderUseCase {</pre><pre>    private final OrderRepository repository;</pre><pre>    public CreateOrderUseCase(<br>            OrderRepository repository) {</pre><pre>        this.repository = repository;<br>    }</pre><pre>    public void execute(Order order) {</pre><pre>        // Business Rule</pre><pre>        repository.save(order);<br>    }<br>}</pre><p>Interface:</p><pre>public interface OrderRepository {<br>    void save(Order order);<br>}</pre><p>Infrastructure:</p><pre>@Repository<br>public class MySQLOrderRepository<br>        implements OrderRepository {<br>    private final JdbcTemplate jdbcTemplate;<br>    public MySQLOrderRepository(<br>            JdbcTemplate jdbcTemplate) {<br>        this.jdbcTemplate = jdbcTemplate;<br>    }<br>    @Override<br>    public void save(Order order) {<br>        jdbcTemplate.update(<br>            &quot;INSERT INTO orders ...&quot;,<br>            order.getId()<br>        );<br>    }<br>}</pre><p>Dependency:</p><pre>┌─────────────────────────┐<br>│     CreateOrderUseCase  │<br>│                         │<br>│ Business Rules          │<br>└────────────┬────────────┘<br>             │<br>             │ depends on<br>             ▼<br>┌─────────────────────────┐<br>│    OrderRepository      │<br>│       &lt;&lt;interface&gt;&gt;     │<br>└────────────▲────────────┘<br>             │<br>             │ implements<br>             │<br>┌────────────┴────────────┐<br>│ MySQLOrderRepository    │<br>│                         │<br>│ JDBC / SQL / MySQL      │<br>└─────────────────────────┘</pre><p>Business Logic จึงไม่จำเป็นต้องรู้จัก</p><pre>JDBC<br>MySQL<br>SQL<br>Connection Pool<br>Database Driver</pre><h3>DIP ไม่ได้หมายความว่า “ทุกอย่างต้องมี Interface”</h3><p>นี่เป็นเรื่องที่อยากเน้นมาก</p><p>บางครั้งเราเห็น Code แบบนี้:</p><pre>interface UserService {<br>    ...<br>}</pre><pre>class UserServiceImpl<br>        implements UserService {<br>    ...<br>}</pre><p>แล้วคิดว่า</p><blockquote><em>“นี่คือ DIP”</em></blockquote><p><strong>ไม่จำเป็นต้องเป็นแบบนั้น</strong></p><p>ถ้า Interface ไม่มีประโยชน์อะไร และมี Implementation เพียงตัวเดียวตลอดอายุระบบ การสร้าง Interface อาจเพิ่มความซับซ้อนโดยไม่จำเป็น</p><p>ตัวอย่าง:</p><pre>interface StringFormatter {<br>    String format(String text);<br>}</pre><pre>class StringFormatterImpl<br>        implements StringFormatter {<br>}</pre><p>ถ้าไม่มีเหตุผลที่จะเปลี่ยน Implementation หรือไม่มี Boundary ที่ต้องการ Abstraction</p><p>Interface นี้อาจไม่ได้ช่วยอะไร</p><h3>แล้วเมื่อไหร่ควรใช้ DIP?</h3><p>มองหา <strong>Boundary</strong> ที่มีโอกาสเปลี่ยนแปลง</p><p>ตัวอย่างเช่น:</p><h3>Database</h3><pre>PostgreSQL<br>MySQL<br>MongoDB</pre><p>สร้าง:</p><pre>Repository</pre><h3>External API</h3><pre>Payment Provider<br>Shipping Provider<br>SMS Provider<br>Email Provider</pre><p>สร้าง:</p><pre>PaymentGateway<br>ShippingGateway<br>SmsSender<br>EmailSender</pre><h3>Infrastructure</h3><pre>Redis<br>Kafka<br>S3<br>File System</pre><p>สร้าง abstraction ตามสิ่งที่ Business ต้องการ</p><h3>DIP ช่วยเรื่อง Changeability</h3><p>สมมติวันนี้ระบบใช้</p><pre>MySQL</pre><p>พรุ่งนี้เปลี่ยนเป็น</p><pre>PostgreSQL</pre><p>ถ้าไม่มี DIP:</p><pre>Business Logic<br>      |<br>      v<br>    MySQL</pre><p>การเปลี่ยน Database อาจกระทบ Business Logic</p><p>แต่ถ้ามี DIP:</p><pre>             Repository<br>                 ^<br>                / \<br>               /   \<br>            MySQL  PostgreSQL</pre><p>Business Logic ไม่ต้องเปลี่ยน</p><p>เปลี่ยนเฉพาะ Infrastructure</p><p>นี่คือหนึ่งในประโยชน์ที่สำคัญที่สุดของ DIP:</p><blockquote><strong><em>ทำให้รายละเอียดทางเทคนิคสามารถเปลี่ยนได้ โดยไม่กระทบ Business Ruleล</em></strong></blockquote><h3>สรุป DIP แบบเข้าใจง่าย</h3><p>Dependency Inversion Principle ไม่ได้หมายความว่า</p><blockquote><em>“ต้องใช้ Interface ทุกครั้ง”</em></blockquote><p>แต่หมายถึง</p><blockquote><strong><em>Business Logic ไม่ควรถูกผูกติดกับรายละเอียดทางเทคนิค</em></strong></blockquote><p>Business ควรกำหนด <strong>Contract</strong> ที่ตัวเองต้องการ</p><p>แล้ว Infrastructure เป็นฝ่ายมา Implement Contract นั้น</p><p>เช่น:</p><pre>Business ต้องการ:<br>&quot;ฉันต้องการบันทึก Order&quot;<br>↓<br>OrderRepository<br>↓<br>Infrastructure:<br>&quot;MySQLOrderRepository&quot;<br>&quot;PostgreSQLOrderRepository&quot;<br>&quot;MongoOrderRepository&quot;</pre><p>ดังนั้น:</p><pre>Business<br>   |<br>   v<br>Abstraction<br>   ^<br>   |<br>Implementation</pre><p>แทนที่จะเป็น:</p><pre>Business<br>   |<br>   v<br>Implementation</pre><h3>จำ DIP ด้วยประโยคเดียว</h3><p>ถ้าต้องจำเพียงประโยคเดียว ผมแนะนำ:</p><blockquote><strong><em>“Business ไม่ควรรู้ว่า Infrastructure ทำงานอย่างไร — Business ควรรู้เพียงว่าตัวเองต้องการอะไร”</em></strong></blockquote><p>หรือจำภาษาอังกฤษจาก SOLID:</p><blockquote><strong><em>High-level modules should not depend on low-level modules. Both should depend on abstractions.</em></strong></blockquote><p>และอีกประโยคที่สำคัญไม่แพ้กัน:</p><blockquote><strong><em>Abstractions should not depend on details. Details should depend on abstractions.</em></strong></blockquote><h3><strong>นี่คือเหตุผลว่าทำไม DIP จึงไม่ได้เป็นเพียงหลักการของ OOP แต่เป็นหนึ่งในแนวคิดพื้นฐานของการออกแบบ Software Architecture ที่สามารถช่วยให้ระบบเปลี่ยนแปลงได้ง่ายขึ้น ทดสอบง่ายขึ้น และลด Coupling ระหว่าง Business Logic กับ Technology ได้อย่างมาก</strong></h3><blockquote>Happy coding</blockquote><blockquote><strong><em>หมายเหตุ:</em></strong><em> บทความนี้เรียบเรียงและปรับภาษาโดยใช้ ChatGPT ช่วย โดยเนื้อหา แนวคิด และตัวอย่างมาจากผู้เขียน</em></blockquote><h3>SOLID Principles</h3><ul><li><a href="https://medium.com/@gdunghi/single-responsibility-principle-srp-solid-principle-b8d9e9962ab4">Single Responsibility Principle (SRP)</a></li><li><a href="https://medium.com/@gdunghi/open-closed-principle-ocp-%E0%B9%80%E0%B8%82%E0%B8%B5%E0%B8%A2%E0%B8%99-code-%E0%B8%A2%E0%B8%B1%E0%B8%87%E0%B9%84%E0%B8%87%E0%B9%83%E0%B8%AB%E0%B9%89%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B1%E0%B8%9A%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%80%E0%B8%9B%E0%B8%A5%E0%B8%B5%E0%B9%88%E0%B8%A2%E0%B8%99%E0%B9%81%E0%B8%9B%E0%B8%A5%E0%B8%87-ed66d0bc0574">Open/Closed Principle (OCP)</a></li><li><a href="https://medium.com/@gdunghi/liskov-substitution-principle-lsp-%E0%B9%80%E0%B8%A1%E0%B8%B7%E0%B9%88%E0%B8%AD-subclass-%E0%B8%84%E0%B8%A7%E0%B8%A3%E0%B9%81%E0%B8%97%E0%B8%99%E0%B8%97%E0%B8%B5%E0%B9%88-parent-%E0%B9%84%E0%B8%94%E0%B9%89%E0%B8%88%E0%B8%A3%E0%B8%B4%E0%B8%87-c7a9b508f850">Liskov Substitution Principle (LSP)</a></li><li><a href="https://medium.com/@gdunghi/interface-segregation-principle-isp-1876c6388962">Interface Segregation Principle (ISP)</a></li><li><a href="https://medium.com/@gdunghi/dependency-inversion-principle-dip-c1df5c344592">Dependency Inversion Principle (DIP)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1df5c344592" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Liskov Substitution Principle (LSP)]]></title>
            <link>https://medium.com/@gdunghi/liskov-substitution-principle-lsp-%E0%B9%80%E0%B8%A1%E0%B8%B7%E0%B9%88%E0%B8%AD-subclass-%E0%B8%84%E0%B8%A7%E0%B8%A3%E0%B9%81%E0%B8%97%E0%B8%99%E0%B8%97%E0%B8%B5%E0%B9%88-parent-%E0%B9%84%E0%B8%94%E0%B9%89%E0%B8%88%E0%B8%A3%E0%B8%B4%E0%B8%87-c7a9b508f850?source=rss-4570570b2ddb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7a9b508f850</guid>
            <category><![CDATA[lsp]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Jirayu Photisan]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 11:47:02 GMT</pubDate>
            <atom:updated>2026-08-25T02:28:17.463Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kvNvUsXHi3EunDg4w8a0zQ.png" /></figure><p>หลังจากพูดถึง SRP และ OCP ไปแล้ว หลักต่อมาคือ <strong>Liskov Substitution Principle หรือ LSP</strong></p><p>ชื่ออาจฟังดูยาก แต่ถ้าผมต้องอธิบาย LSP แบบสั้น ๆ ผมจะอธิบายว่า</p><blockquote><strong><em>ถ้าผมเปลี่ยน Object จาก Parent เป็น Child แล้ว Program ยังทำงานถูกต้องตามที่คาดหวังหรือไม่?</em></strong></blockquote><p>ถ้าคำตอบคือไม่ได้ เราอาจกำลังใช้ Inheritance ในแบบที่ไม่เหมาะสม</p><h3>ตัวอย่างที่ดูเหมือนถูก</h3><p>สมมติผมมี Bird</p><pre>public class Bird {<br>    public void fly() {<br>        System.out.println(&quot;Flying...&quot;);<br>    }<br>}</pre><p>แล้วสร้าง Penguin</p><pre>public class Penguin extends Bird {<br>}</pre><p>ถ้ามองจากโลกจริง Penguin ก็เป็น Bird</p><pre>Bird<br>  ▲<br>  │<br>Penguin</pre><p>แต่ปัญหาคือ:</p><pre>Bird bird = new Penguin();<br><br>bird.fly();</pre><p>แล้ว Penguin จะบินได้อย่างไร?</p><p>ถ้าผมต้องแก้แบบนี้:</p><pre>public class Penguin extends Bird {<br><br>    @Override<br>    public void fly() {<br>        throw new UnsupportedOperationException();<br>    }<br>}</pre><p>Code สามารถ Compile ได้ แต่ตอน Runtime กลับเกิด Exception</p><p>ตรงนี้แหละครับที่ LSP เริ่มเข้ามาเกี่ยวข้อง</p><h3>LSP บอกอะไร?</h3><p>แนวคิดของ LSP คือ:</p><blockquote><strong><em>Object ของ Subclass ควรสามารถนำมาแทนที่ Object ของ Superclass ได้ โดยไม่ทำให้ความถูกต้องของโปรแกรมเสียไป</em></strong></blockquote><p>พูดในแบบที่ผมใช้จำเองคือ:</p><blockquote><strong><em>ถ้าผมบอกว่า Code นี้รับ </em></strong><strong><em>Bird ผมควรสามารถส่ง </em></strong><strong><em>Penguin เข้าไปได้ โดยไม่ต้องมานั่งลุ้นว่า Method ของ </em></strong><strong><em>Bird จะใช้กับ Penguin ได้หรือไม่</em></strong></blockquote><p>ตัวอย่าง:</p><pre>public void makeBirdFly(Bird bird) {<br>    bird.fly();<br>}</pre><p>ถ้าผมส่ง:</p><pre>makeBirdFly(new Eagle());</pre><p>ทุกอย่างโอเค</p><p>แต่ถ้าส่ง:</p><pre>makeBirdFly(new Penguin());</pre><p>แล้วเกิด Exception</p><p>ผมก็ต้องกลับมาถามแล้วว่า</p><blockquote><strong><em>จริง ๆ แล้ว </em></strong><strong><em>Penguin ควรเป็น </em></strong><strong><em>Bird ใน Abstraction นี้หรือเปล่า?</em></strong></blockquote><h3>ผมจะแก้เป็นแบบนี้</h3><p>แทนที่จะเอา fly() ไปไว้ใน Bird ผมจะแยกความสามารถออกมา</p><pre>public class Bird {<br><br>}</pre><p>แล้วสร้าง:</p><pre>public interface Flyable {<br><br>    void fly();<br>}</pre><p>นกที่บินได้:</p><pre>public class Eagle extends Bird<br>        implements Flyable {<br>    @Override<br>    public void fly() {<br>        System.out.println(&quot;Flying...&quot;);<br>    }<br>}</pre><p>ส่วน Penguin:</p><pre>public class Penguin extends Bird {<br><br>}</pre><p>ตอนนี้ Model สะท้อนความจริงมากขึ้น</p><pre>             Bird<br>            /    \<br>           /      \<br>        Eagle    Penguin<br>          │<br>          │<br>       Flyable</pre><p>ผมไม่ได้บอกว่า Penguin “บินไม่ได้” ด้วยการ Throw Exception</p><p>แต่ผมออกแบบ Type ให้บอกความสามารถของมันตั้งแต่แรก</p><h3>Rectangle กับ Square</h3><p>อีกตัวอย่างหนึ่งที่ผมชอบใช้กับ LSP คือ Rectangle กับ Square</p><p>เพราะตัวอย่างนี้ทำให้เห็นว่า</p><blockquote><strong><em>ความสัมพันธ์แบบ </em></strong><strong><em>is-a ในโลกจริง ไม่ได้หมายความว่า Subclass จะสามารถแทนที่ Parent ใน Software ได้เสมอไป</em></strong></blockquote><p>ในทางคณิตศาสตร์:</p><pre>Square เป็น Rectangle</pre><p>ฟังดูถูก</p><p>แต่ลองดู Code นี้:</p><pre>public class Rectangle {<br><br>    protected int width;<br>    protected int height;<br>    public void setWidth(int width) {<br>        this.width = width;<br>    }<br>    public void setHeight(int height) {<br>        this.height = height;<br>    }<br>    public int area() {<br>        return width * height;<br>    }<br>}</pre><p>แล้วผมสร้าง:</p><pre>public class Square extends Rectangle {<br><br>    @Override<br>    public void setWidth(int width) {<br>        this.width = width;<br>        this.height = width;<br>    }<br>    @Override<br>    public void setHeight(int height) {<br>        this.width = height;<br>        this.height = height;<br>    }<br>}</pre><p>ตอนแรกอาจดูเหมือนถูก</p><p>แต่ลองดู Code ที่ใช้งาน:</p><pre>public void resize(Rectangle rectangle) {<br><br>    rectangle.setWidth(10);<br>    rectangle.setHeight(20);<br><br>    System.out.println(<br>        rectangle.area()<br>    );<br>}</pre><p>ถ้าผมส่ง:</p><pre>resize(new Rectangle());</pre><p>จะได้:</p><pre>width  = 10<br>height = 20<br>area   = 200</pre><p>แต่ถ้าผมส่ง:</p><pre>resize(new Square());</pre><p>มันจะไม่สามารถรักษาพฤติกรรมแบบเดียวกับ Rectangle ได้</p><p>เพราะ Square มีข้อจำกัดว่า:</p><pre>width == height</pre><p>ดังนั้นเมื่อผมทำ:</p><pre>square.setWidth(10);<br>square.setHeight(20);</pre><p>Square ไม่สามารถมีสถานะ:</p><pre>width  = 10<br>height = 20</pre><p>ได้</p><p>มันต้องทำให้ทั้งสองด้านเท่ากัน</p><p>เช่น:</p><pre>width  = 20<br>height = 20</pre><p>หรือ</p><pre>width  = 10<br>height = 10</pre><p>ซึ่งไม่ตรงกับสิ่งที่ Code ที่รับ Rectangle คาดหวัง</p><h3>แต่ตรงนี้มีจุดที่ผมอยากเน้น</h3><p>ปัญหาของตัวอย่างนี้ <strong>ไม่ได้อยู่ที่การคำนวณพื้นที่</strong></p><p>สูตร:</p><pre>width × height</pre><p>ของ Rectangle ก็ถูก</p><p>และของ Square ก็ถูก</p><p>ถ้าเป็น Square ด้านยาว 10:</p><pre>10 × 10 = 100</pre><p>ถ้าเป็น Rectangle กว้าง 10 สูง 20:</p><pre>10 × 20 = 200</pre><p>ดังนั้นเราไม่ได้มีปัญหาเพราะ area() คำนวณผิด</p><p><strong>ปัญหาอยู่ที่ Contract ของ </strong><strong>Rectangle</strong></p><p>Rectangle กำลังบอกคนที่ใช้งานว่า:</p><pre>rectangle.setWidth(10);<br>rectangle.setHeight(20);</pre><p>สามารถกำหนด Width และ Height แยกจากกันได้</p><p>แต่ Square ไม่สามารถทำตาม Contract นี้ได้</p><p>เพราะธรรมชาติของ Square คือ:</p><pre>width == height</pre><p>ดังนั้นถ้า Code บอกว่า:</p><pre>Rectangle rectangle</pre><p>ผมไม่สามารถเอา Square มาแทนที่ได้โดยยังรับประกันพฤติกรรมเดิม</p><p><strong>นี่คือ LSP Violation</strong></p><h3>ผมจะแก้เป็นแบบนี้</h3><p>ผมจะไม่พยายามแก้ Square ให้สามารถเป็น Rectangle ได้</p><p>แต่ผมจะกลับไปดู Abstraction ใหม่</p><p>ถ้าสิ่งที่ผมต้องการจริง ๆ คือ “สิ่งที่สามารถคำนวณพื้นที่ได้”</p><p>ผมจะสร้าง:</p><pre>public interface Shape {<br><br>    int area();<br>}</pre><p>จากนั้น:</p><pre>public class Rectangle implements Shape {<br><br>    private final int width;<br>    private final int height;<br>    public Rectangle(int width, int height) {<br>        this.width = width;<br>        this.height = height;<br>    }<br>    @Override<br>    public int area() {<br>        return width * height;<br>    }<br>}</pre><p>และ:</p><pre>public class Square implements Shape {<br><br>    private final int side;<br><br>    public Square(int side) {<br>        this.side = side;<br>    }<br>    @Override<br>    public int area() {<br>        return side * side;<br>    }<br>}</pre><p>ตอนนี้ทั้งสองตัวสามารถใช้แทน Shape ได้</p><pre>public int calculateArea(Shape shape) {<br>    return shape.area();<br>}</pre><p>ผมสามารถส่ง:</p><pre>calculateArea(<br>    new Rectangle(10, 20)<br>);</pre><p>หรือ:</p><pre>calculateArea(<br>    new Square(10)<br>);</pre><p>ได้เหมือนกัน</p><p>เพราะ Contract ของ Shape มีเพียง:</p><pre>area()</pre><p>และทั้งสองตัวสามารถรับประกัน Contract นี้ได้</p><pre>Shape<br>                ▲<br>        ┌───────┴───────┐<br>        │               │<br>        ▼               ▼<br>    Rectangle         Square<br>        │               │<br>      area()           area()</pre><p>ตรงนี้จึงเป็นการออกแบบที่เหมาะสมกว่า</p><h3>สิ่งที่ผมได้จากตัวอย่าง Rectangle / Square</h3><p>สำหรับผม จุดสำคัญของตัวอย่างนี้ไม่ใช่เรื่องว่า:</p><blockquote><em>“Square ไม่ควร extends Rectangle”</em></blockquote><p>แบบท่องจำ</p><p>แต่คือการถามว่า:</p><blockquote><strong><em>“Abstraction ที่เราสร้างขึ้นมา กำลังรับประกันอะไรกับคนที่เรียกมัน?”</em></strong></blockquote><p>ถ้า Rectangle มี Contract ว่า:</p><pre>setWidth()<br>setHeight()</pre><p>สามารถเปลี่ยนแยกกันได้</p><p>แต่ Square ไม่สามารถทำตาม Contract นี้ได้</p><p>ผมก็ไม่ควรเอา Square มาเป็น Subclass ของ Rectangle ใน Model นี้</p><p>และบางครั้งวิธีแก้ LSP ที่ดีที่สุดไม่ใช่การแก้ Subclass</p><p>แต่คือ:</p><blockquote><strong><em>กลับไปแก้ Abstraction ตั้งแต่ต้น</em></strong></blockquote><h3>LSP ไม่ได้บอกว่า “ห้ามใช้ Inheritance”</h3><p>ตรงนี้สำคัญ</p><p>LSP ไม่ได้หมายความว่า:</p><blockquote><em>“Inheritance ไม่ดี”</em></blockquote><p>หรือ:</p><blockquote><em>“อย่าใช้ extends”</em></blockquote><p>Inheritance ยังมีประโยชน์ ถ้า Subclass สามารถรักษา Contract ของ Parent ได้</p><p>เช่น:</p><pre>public class Animal {<br><br>    public void eat() {<br>        System.out.println(&quot;Eating...&quot;);<br>    }<br>}</pre><pre>public class Dog extends Animal {<br><br>}</pre><pre>public class Cat extends Animal {<br><br>}</pre><p>ผมสามารถเขียน:</p><pre>public void feed(Animal animal) {<br>    animal.eat();<br>}</pre><p>แล้วส่ง:</p><pre>feed(new Dog());<br>feed(new Cat());</pre><p>ได้โดยไม่ต้องมีเงื่อนไขพิเศษ</p><p>นี่คือสิ่งที่ผมต้องการจาก LSP</p><h3>สิ่งที่สำคัญกว่าคำว่า “is-a”</h3><p>นี่เป็นสิ่งที่ผมคิดว่าสำคัญที่สุดของ LSP</p><p>เวลาออกแบบ Class ผมอาจคิดว่า:</p><pre>Penguin is a Bird<br>Square is a Rectangle</pre><p>ในโลกจริงอาจถูกต้อง</p><p>แต่ใน Code ผมต้องถามเพิ่มว่า:</p><blockquote><strong><em>“มันสามารถทำตัวแทนกันได้ตาม Contract ที่กำหนดไว้หรือไม่?”</em></strong></blockquote><p>เพราะ:</p><pre>is-a</pre><p>ในโลกจริง</p><p>ไม่ได้แปลว่า:</p><pre>substitutable-for</pre><p>ใน Software เสมอไป</p><p>ดังนั้นเวลาผมเห็น:</p><pre>class Child extends Parent</pre><p>ผมจะไม่ถามแค่ว่า:</p><blockquote><em>“Child เป็น Parent หรือเปล่า?”</em></blockquote><p>แต่ผมจะถามว่า:</p><blockquote><strong><em>“ถ้าผมเอา Child ไปแทน Parent แล้ว Code ที่มีอยู่ยังทำงานถูกต้องหรือไม่?”</em></strong></blockquote><h3>LSP กับ Contract</h3><p>ผมชอบคิดว่า Parent Class หรือ Interface กำลังให้ <strong>Contract</strong> กับคนที่เรียกมัน</p><p>เช่น:</p><pre>public interface Payment {<br>    void pay(Money amount);<br>}</pre><p>คนที่เรียก:</p><pre>public void checkout(<br>        Payment payment,<br>        Money amount) {<br><br>    payment.pay(amount);<br>}</pre><p>ผมกำลังบอกกับ checkout() ว่า:</p><blockquote><em>“ไม่ว่าคุณจะส่ง Payment Implementation ตัวไหนมา ผมจะเรียก </em><em>pay() และมันต้องทำงานตาม Contract ของ Payment&quot;</em></blockquote><p>ดังนั้น Implementation:</p><pre>CreditCardPayment<br>BankTransferPayment<br>WalletPayment</pre><p>ควรสามารถแทนที่ Payment ได้</p><pre>Payment<br>                    ▲<br>          ┌─────────┼──────────┐<br>          │         │          │<br>          ▼         ▼          ▼<br>      CreditCard   Bank       Wallet<br>       Payment    Transfer    Payment</pre><p>ถ้า WalletPayment กลับโยน:</p><pre>throw new UnsupportedOperationException();</pre><p>ทุกครั้งที่เรียก pay()</p><p>ผมต้องกลับมาดูแล้วว่า Contract ของ Payment ถูกออกแบบไว้ถูกหรือไม่</p><h3>แล้วถ้า Subclass มีข้อจำกัดมากกว่า Parent?</h3><p>ตรงนี้ก็เป็นสัญญาณที่ผมใช้ดู LSP</p><p>สมมติ Parent บอกว่า:</p><pre>public void withdraw(Money amount) {<br>    // withdraw money<br>}</pre><p>แต่ Subclass บอกว่า:</p><pre>@Override<br>public void withdraw(Money amount) {<br><br>    if (amount.isGreaterThan(Money.of(1000))) {<br>        throw new UnsupportedOperationException();<br>    }<br>}</pre><p>ถ้า Code ที่ใช้ Parent สามารถถอน 10,000 ได้</p><p>แต่พอเปลี่ยนเป็น Subclass กลับทำไม่ได้</p><p>ผมจะถามว่า:</p><blockquote><strong><em>Subclass ยังรักษา Contract ของ Parent อยู่หรือไม่?</em></strong></blockquote><p>ถ้าไม่ นี่ก็เป็นสัญญาณของ LSP Violation</p><h3>ผมจะจำ LSP แบบง่าย ๆ</h3><p>เวลาผมเห็น:</p><pre>class Child extends Parent</pre><p>ผมจะไม่ถามแค่ว่า:</p><blockquote><em>“Child เป็น Parent หรือเปล่า?”</em></blockquote><p>แต่จะถามว่า:</p><blockquote><strong><em>“ถ้าผมเอา Child ไปแทน Parent แล้ว Code ที่มีอยู่ยังทำงานถูกต้องตาม Contract เดิมหรือไม่?”</em></strong></blockquote><p>ถ้าได้:</p><pre>Parent<br>  ▲<br>  │<br>Child</pre><pre>Child แทน Parent ได้<br>        ↓<br>      LSP ✓</pre><p>แต่ถ้าผมต้องเขียน:</p><pre>if (object instanceof Child) {<br>    // special case<br>}</pre><p>หรือ:</p><pre>throw new UnsupportedOperationException();</pre><p>หรือมีคำอธิบายว่า:</p><pre>&quot;ถ้าเป็น Child ห้ามเรียก Method นี้&quot;</pre><p>ผมจะเริ่มสงสัยทันทีว่า Design ตรงนั้นมีปัญหาเรื่อง LSP หรือไม่</p><h3>สรุป</h3><p>สำหรับผม LSP ไม่ได้เป็นเรื่องของการจำว่า:</p><blockquote><strong><em>“Subclass ต้องสามารถแทนที่ Parent ได้”</em></strong></blockquote><p>แล้วจบ</p><p>สิ่งที่สำคัญกว่าคือ <strong>Contract</strong></p><p>ถ้า Code บอกว่า:</p><pre>process(Payment payment)</pre><p>ผมควรสามารถส่ง CreditCardPayment, BankTransferPayment หรือ WalletPayment เข้าไปได้ โดยไม่ต้องแก้ process() หรือเขียนเงื่อนไขพิเศษเพื่อจัดการแต่ละ Subclass</p><p>ส่วนกรณี Rectangle / Square ก็เช่นเดียวกัน</p><p>ปัญหาไม่ได้อยู่ที่:</p><pre>Rectangle → width × height<br>Square    → width × height</pre><p>เพราะทั้งสองตัวคำนวณพื้นที่ได้ถูกต้อง</p><p>ปัญหาอยู่ที่ Rectangle มี Contract ที่อนุญาตให้:</p><pre>เปลี่ยน Width<br>เปลี่ยน Height</pre><p>แยกจากกันได้ ในขณะที่ Square ไม่สามารถรักษา Contract นี้ได้</p><p>ดังนั้นการแก้ที่เหมาะสมอาจไม่ใช่การแก้ Square แต่เป็นการ <strong>ออกแบบ Abstraction ใหม่ให้สะท้อนสิ่งที่ทั้งสองตัวสามารถรับประกันร่วมกันได้</strong></p><p>สำหรับผม นี่คือหัวใจของ LSP:</p><blockquote><strong><em>ถ้า Subclass ไม่สามารถทำตาม Contract ที่คนใช้ Parent คาดหวังได้ บางทีปัญหาอาจไม่ได้อยู่ที่ Subclass แต่อยู่ที่การออกแบบ Abstraction ตั้งแต่แรก</em></strong></blockquote><p>ถึงตรงนี้แล้วไปต่อกันที่หัวข้อถัดไป <a href="https://medium.com/@gdunghi/interface-segregation-principle-isp-1876c6388962">Interface Segregation Principle (ISP)</a></p><blockquote>Happy coding</blockquote><blockquote><strong><em>หมายเหตุ:</em></strong><em> บทความนี้เรียบเรียงและปรับภาษาโดยใช้ ChatGPT ช่วย โดยเนื้อหา แนวคิด และตัวอย่างมาจากผู้เขียน</em></blockquote><h3>SOLID Principles</h3><ul><li><a href="https://medium.com/@gdunghi/single-responsibility-principle-srp-solid-principle-b8d9e9962ab4">Single Responsibility Principle (SRP)</a></li><li><a href="https://medium.com/@gdunghi/open-closed-principle-ocp-%E0%B9%80%E0%B8%82%E0%B8%B5%E0%B8%A2%E0%B8%99-code-%E0%B8%A2%E0%B8%B1%E0%B8%87%E0%B9%84%E0%B8%87%E0%B9%83%E0%B8%AB%E0%B9%89%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B1%E0%B8%9A%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%80%E0%B8%9B%E0%B8%A5%E0%B8%B5%E0%B9%88%E0%B8%A2%E0%B8%99%E0%B9%81%E0%B8%9B%E0%B8%A5%E0%B8%87-ed66d0bc0574">Open/Closed Principle (OCP)</a></li><li><a href="https://medium.com/@gdunghi/liskov-substitution-principle-lsp-%E0%B9%80%E0%B8%A1%E0%B8%B7%E0%B9%88%E0%B8%AD-subclass-%E0%B8%84%E0%B8%A7%E0%B8%A3%E0%B9%81%E0%B8%97%E0%B8%99%E0%B8%97%E0%B8%B5%E0%B9%88-parent-%E0%B9%84%E0%B8%94%E0%B9%89%E0%B8%88%E0%B8%A3%E0%B8%B4%E0%B8%87-c7a9b508f850">Liskov Substitution Principle (LSP)</a></li><li><a href="https://medium.com/@gdunghi/interface-segregation-principle-isp-1876c6388962">Interface Segregation Principle (ISP)</a></li><li><a href="https://medium.com/@gdunghi/dependency-inversion-principle-dip-c1df5c344592">Dependency Inversion Principle (DIP)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7a9b508f850" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Open/Closed Principle (OCP) — เขียน Code ยังไงให้รองรับการเปลี่ยนแปลง]]></title>
            <link>https://medium.com/@gdunghi/open-closed-principle-ocp-%E0%B9%80%E0%B8%82%E0%B8%B5%E0%B8%A2%E0%B8%99-code-%E0%B8%A2%E0%B8%B1%E0%B8%87%E0%B9%84%E0%B8%87%E0%B9%83%E0%B8%AB%E0%B9%89%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B1%E0%B8%9A%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%80%E0%B8%9B%E0%B8%A5%E0%B8%B5%E0%B9%88%E0%B8%A2%E0%B8%99%E0%B9%81%E0%B8%9B%E0%B8%A5%E0%B8%87-ed66d0bc0574?source=rss-4570570b2ddb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed66d0bc0574</guid>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Jirayu Photisan]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 09:20:54 GMT</pubDate>
            <atom:updated>2026-08-25T02:27:41.324Z</atom:updated>
            <content:encoded><![CDATA[<h3>Open/Closed Principle (OCP) — เขียน Code ยังไงให้รองรับการเปลี่ยนแปลง</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8-DUtmtxoe-XYLDnWj9fhA.png" /></figure><p>หลังจากบทความก่อนหน้าที่ผมพูดถึง <strong>Single Responsibility Principle (SRP)</strong> ไปแล้ว หลักต่อมาที่ผมอยากพูดถึงคือ <strong>Open/Closed Principle หรือ OCP</strong></p><p>ตอนแรกที่ผมเจอ OCP ผมจำมันได้แค่ประโยคเดียว</p><blockquote><strong><em>Open for extension, closed for modification</em></strong></blockquote><p>ตอนนั้นผมเข้าใจง่าย ๆ ว่า</p><blockquote><em>“ห้ามแก้ Code เดิม”</em></blockquote><p>ซึ่งพอเอาไปใช้จริง มันไม่ใช่แบบนั้น</p><p>ถ้า Requirement เปลี่ยน แต่เราห้ามแก้ Code เดิมเลย ระบบก็คงพัฒนาไม่ได้</p><p>สิ่งที่ผมเข้าใจมากขึ้นหลังจากเขียนระบบมาสักพักคือ</p><blockquote><strong><em>OCP ไม่ได้บอกว่าเราห้ามแก้ Code แต่บอกว่าเราควรออกแบบ Code บางส่วนให้สามารถรองรับการเพิ่มความสามารถใหม่ โดยไม่ต้องกลับไปแก้ Logic เดิมซ้ำ ๆ</em></strong></blockquote><h3>ลองดูตัวอย่างง่าย ๆ</h3><p>สมมติผมมีระบบคำนวณส่วนลด</p><p>ตอนแรกมีลูกค้าแค่ 2 ประเภท</p><pre>public class DiscountCalculator {<br>     public Money calculate(Customer customer) {<br>        if (customer.isRegular()) {<br>            return customer.getPrice()<br>                    .multiply(0.05);<br>        }<br>        if (customer.isPremium()) {<br>            return customer.getPrice()<br>                    .multiply(0.10);<br>        }<br>        return Money.zero();<br>    }<br>}</pre><p>ตอนนี้ไม่มีอะไรน่ากังวล</p><p>แต่วันหนึ่ง Business เดินมาบอกผมว่า</p><pre>VIP       ลด 20%<br>Employee  ลด 30%<br>Partner   ลด 15%</pre><p>สิ่งที่ผมต้องทำคือกลับมาแก้ DiscountCalculator</p><pre>if (customer.isVip()) {<br>    return customer.getPrice()<br>            .multiply(0.20);<br>}<br><br>if (customer.isEmployee()) {<br>    return customer.getPrice()<br>            .multiply(0.30);<br>}<br>if (customer.isPartner()) {<br>    return customer.getPrice()<br>            .multiply(0.15);<br>}</pre><p>ตอนนี้ผมเริ่มเห็นปัญหาแล้ว</p><p>ทุกครั้งที่มี Discount Type ใหม่ ผมต้องกลับมาแก้ Code เดิม</p><p>ถ้ามี 10 ประเภทก็มี if 10 อัน</p><p>ถ้ามี 20 ประเภทก็มี if 20 อัน</p><p>และที่สำคัญคือ DiscountCalculator ต้องรู้จัก Discount ทุกประเภท</p><h3>ผมจะแก้เป็นแบบนี้</h3><p>ผมจะสร้าง Abstraction ขึ้นมาก่อน</p><pre>public interface DiscountPolicy {<br>    Money calculate(Customer customer);<br>}</pre><p>จากนั้นแต่ละประเภทก็รับผิดชอบของตัวเอง</p><pre>public class RegularDiscount<br>        implements DiscountPolicy {<br>    @Override<br>    public Money calculate(Customer customer) {<br>        return customer.getPrice()<br>                .multiply(0.05);<br>    }<br>}</pre><pre>public class PremiumDiscount<br>        implements DiscountPolicy {<br><br>    @Override<br>    public Money calculate(Customer customer) {<br>        return customer.getPrice()<br>                .multiply(0.10);<br>    }<br>}</pre><p>ถ้ามี VIP เพิ่มขึ้นมา ผมก็สร้างใหม่</p><pre>public class VipDiscount<br>        implements DiscountPolicy {<br><br>    @Override<br>    public Money calculate(Customer customer) {<br>        return customer.getPrice()<br>                .multiply(0.20);<br>    }<br>}</pre><p>สิ่งที่ผมชอบตรงนี้คือ</p><p><strong>ผมไม่ได้กลับไปแก้ Logic เดิมเพื่อเพิ่ม VIP</strong></p><p>ผมแค่เพิ่มความสามารถใหม่เข้ามา</p><pre>DiscountPolicy<br>      ▲<br>      │<br> ┌────┼────────┐<br> │    │        │<br> ▼    ▼        ▼<br>Regular Premium VIP</pre><p>นี่คือแนวคิดของ <strong>Open/Closed Principle</strong></p><h3>แล้วคำว่า “Closed for Modification” หมายถึงอะไร?</h3><p>ตรงนี้ผมคิดว่าเป็นจุดที่หลายคนเข้าใจผิด</p><p>มันไม่ได้หมายความว่า</p><blockquote><em>“Class นี้ห้ามแก้ตลอดชีวิต”</em></blockquote><p>แต่ผมจะมองว่า</p><blockquote><strong><em>ถ้า Code ส่วนหนึ่งมีหน้าที่ที่ Stable แล้ว การเพิ่ม Feature ใหม่ไม่ควรทำให้เราต้องกลับไปแก้ Logic เดิมทุกครั้ง</em></strong></blockquote><p>ในตัวอย่างนี้</p><pre>DiscountCalculator<br>        │<br>        ▼<br>DiscountPolicy</pre><p>ผมอยากให้ส่วนที่เป็น Business Flow พึ่งพา DiscountPolicy</p><p>ส่วน Discount ใหม่ก็เพิ่ม Implementation เข้ามา</p><pre>DiscountPolicy<br>                  ▲<br>       ┌──────────┼──────────┐<br>       │          │          │<br>       ▼          ▼          ▼<br>   Regular     Premium       VIP</pre><p>ดังนั้นถ้าพรุ่งนี้มี</p><pre>Partner<br>Employee<br>Gold<br>BlackCard<br>Corporate</pre><p>ผมสามารถเพิ่ม Class ใหม่ได้ โดยไม่ต้องกลับไปเพิ่ม if ใน Logic เดิม</p><h3>ไม่ได้ใช้ OCP กับทุกอย่าง</h3><p>หลังจากศึกษา OCP แล้ว ผมเคยเห็น Code บางแบบที่พยายามสร้าง Interface ทุกอย่าง</p><p>เช่น</p><pre>UserService<br>UserServiceImpl<br><br>UserRepository<br>UserRepositoryImpl<br><br>UserValidator<br>UserValidatorImpl<br><br>UserMapper<br>UserMapperImpl</pre><p>แล้วบอกว่า</p><blockquote><em>“นี่คือ SOLID”</em></blockquote><p>ผมไม่คิดว่าจำเป็น</p><p>ถ้าผมมี Code แบบนี้:</p><pre>public class UserValidator {<br>    public boolean validate(User user) {<br>        ...<br>    }<br>}</pre><p>และผมไม่ได้มี Requirement ว่าจะมี Validator หลายแบบ</p><p>ผมก็ไม่จำเป็นต้องรีบสร้าง</p><pre>interface UserValidator</pre><p>เพียงเพราะต้องการทำตาม OCP</p><p>สำหรับผม OCP ควรนำมาใช้ตรง <strong>จุดที่มีแนวโน้มว่าจะมีการเปลี่ยนแปลงหรือมี Extension จริง ๆ</strong></p><h3>OCP กับ SRP</h3><p>ผมมองว่า SRP และ OCP ค่อนข้างเกี่ยวข้องกัน</p><p>SRP ทำให้เราถามว่า</p><blockquote><strong><em>“Class นี้รับผิดชอบอะไร?”</em></strong></blockquote><p>และลึกลงไปอีกคือ</p><blockquote><strong><em>“อะไรคือเหตุผลที่ทำให้ Class นี้ต้องเปลี่ยน?”</em></strong></blockquote><p>ส่วน OCP ทำให้ผมถามต่อว่า</p><blockquote><strong><em>“ถ้า Requirement ประเภทนี้เปลี่ยน ผมสามารถเพิ่มความสามารถใหม่โดยไม่ต้องกลับมาแก้ Logic เดิมได้หรือไม่?”</em></strong></blockquote><p>ตัวอย่าง Discount จึงค่อนข้างชัด</p><p>ถ้าผมเอาทุกอย่างไว้ใน Class เดียว:</p><pre>DiscountCalculator<br>│<br>├── Regular<br>├── Premium<br>├── VIP<br>├── Employee<br>├── Partner<br>└── Corporate</pre><p>ทุกครั้งที่มีประเภทใหม่ ผมต้องกลับมาแก้ Class เดิม</p><p>แต่ถ้าผมแยก Responsibility และใช้ Abstraction:</p><pre>DiscountPolicy<br>      ▲<br>      │<br> ┌────┼─────────────┐<br> │    │             │<br> ▼    ▼             ▼<br>Regular Premium     VIP</pre><p>การเพิ่มประเภทใหม่ก็กลายเป็นการเพิ่ม Implementation</p><h3>แต่ OCP ก็มี Cost</h3><p>สิ่งหนึ่งที่ผมคิดว่าต้องระวังคือ <strong>อย่าพยายามทำทุกอย่างให้รองรับ Extension ตั้งแต่วันแรก</strong></p><p>สมมติระบบผมมี Discount แค่:</p><pre>Regular<br>Premium</pre><p>และผมรู้แน่ ๆ ว่าจะไม่มีประเภทอื่น</p><p>ผมอาจเขียนแบบง่าย ๆ ก่อนก็ได้</p><pre>if (customer.isRegular()) {<br>    ...<br>}<br><br>if (customer.isPremium()) {<br>    ...<br>}</pre><p>มันอาจจะอ่านง่ายกว่า</p><p>การสร้าง:</p><pre>DiscountPolicy<br>RegularDiscount<br>PremiumDiscount<br>DiscountFactory<br>DiscountResolver</pre><p>ทั้งที่ระบบยังมีแค่ 2 แบบ</p><p>สำหรับผม แบบหลังอาจเป็น <strong>Over-engineering</strong></p><p>ดังนั้น OCP ไม่ใช่คำสั่งว่า</p><blockquote><em>“ต้องใช้ Interface เสมอ”</em></blockquote><p>แต่เป็นแนวคิดว่า</p><blockquote><strong><em>เมื่อผมเห็นจุดที่มีแนวโน้มจะเปลี่ยน ผมควรออกแบบ Boundary ตรงนั้นให้รองรับการขยายได้</em></strong></blockquote><h3>ผมจะจำ OCP แบบนี้</h3><p>ถ้าเจอ Code แบบนี้:</p><pre>if (type == A) {<br>    ...<br>}<br><br>if (type == B) {<br>    ...<br>}<br><br>if (type == C) {<br>    ...<br>}</pre><p>ผมจะยังไม่รีบ Refactor ทันที</p><p>ผมจะถามก่อนว่า</p><blockquote><strong><em>“Type นี้มีโอกาสเพิ่มอีกไหม?”</em></strong></blockquote><p>ถ้าคำตอบคือ “มีแน่นอน”</p><p>ผมอาจเปลี่ยนเป็น:</p><pre>Policy<br>                  ▲<br>        ┌─────────┼─────────┐<br>        │         │         │<br>        ▼         ▼         ▼<br>        A         B         C</pre><p>แล้วเมื่อมี D:</p><pre>Policy<br>                  ▲<br>        ┌─────────┼─────────┬─────<br>        │         │         │<br>        ▼         ▼         ▼<br>        A         B         C      D</pre><p>ผมแค่เพิ่ม D</p><p>ไม่ต้องกลับไปแก้ Logic ที่จัดการ A, B, C</p><h3>สรุป</h3><p>สำหรับผม OCP ไม่ใช่เรื่องของการสร้าง Interface ให้เยอะที่สุด</p><p>มันคือการมองหา <strong>จุดที่มีแนวโน้มจะเปลี่ยน</strong> แล้วออกแบบตรงนั้นให้สามารถเพิ่มความสามารถใหม่ได้ โดยไม่ต้องแก้ Code เดิมซ้ำ ๆ</p><p>จำง่าย ๆ:</p><pre>SRP<br>↓<br>แยก Responsibility ให้ชัด<br><br><br>OCP<br>↓<br>เพิ่มความสามารถใหม่<br>โดยลดการแก้ Logic เดิม</pre><p>สุดท้ายแล้วประโยค</p><blockquote><strong><em>Open for extension, closed for modification</em></strong></blockquote><p>สำหรับผมจึงไม่ได้หมายความว่า</p><blockquote><em>“ห้ามแก้ Code”</em></blockquote><p>แต่หมายถึง</p><blockquote><strong><em>“ผมอยากให้ Code ส่วนที่ Stable อยู่แล้ว ไม่ต้องถูกลากกลับมาแก้ทุกครั้งที่มี Feature ใหม่เข้ามา”</em></strong></blockquote><p>และนี่คือเหตุผลที่ผมมองว่า OCP เป็นเรื่องของ <strong>การออกแบบเพื่อรองรับ Change</strong> มากกว่าการเป็นกฎว่า “ต้องใช้ Interface”</p><p>ถึงตรงนี้แล้ว ไปต่อกันหัวข้อถัดไป <a href="https://medium.com/@gdunghi/liskov-substitution-principle-lsp-%E0%B9%80%E0%B8%A1%E0%B8%B7%E0%B9%88%E0%B8%AD-subclass-%E0%B8%84%E0%B8%A7%E0%B8%A3%E0%B9%81%E0%B8%97%E0%B8%99%E0%B8%97%E0%B8%B5%E0%B9%88-parent-%E0%B9%84%E0%B8%94%E0%B9%89%E0%B8%88%E0%B8%A3%E0%B8%B4%E0%B8%87-c7a9b508f850">Liskov Substitution Principle (LSP)</a></p><blockquote>Happy coding</blockquote><blockquote><strong><em>หมายเหตุ:</em></strong><em> บทความนี้เรียบเรียงและปรับภาษาโดยใช้ ChatGPT ช่วย โดยเนื้อหา แนวคิด และตัวอย่างมาจากผู้เขียน</em></blockquote><h3>SOLID Principles</h3><ul><li><a href="https://medium.com/@gdunghi/single-responsibility-principle-srp-solid-principle-b8d9e9962ab4">Single Responsibility Principle (SRP)</a></li><li><a href="https://medium.com/@gdunghi/open-closed-principle-ocp-%E0%B9%80%E0%B8%82%E0%B8%B5%E0%B8%A2%E0%B8%99-code-%E0%B8%A2%E0%B8%B1%E0%B8%87%E0%B9%84%E0%B8%87%E0%B9%83%E0%B8%AB%E0%B9%89%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B1%E0%B8%9A%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%80%E0%B8%9B%E0%B8%A5%E0%B8%B5%E0%B9%88%E0%B8%A2%E0%B8%99%E0%B9%81%E0%B8%9B%E0%B8%A5%E0%B8%87-ed66d0bc0574">Open/Closed Principle (OCP)</a></li><li><a href="https://medium.com/@gdunghi/liskov-substitution-principle-lsp-%E0%B9%80%E0%B8%A1%E0%B8%B7%E0%B9%88%E0%B8%AD-subclass-%E0%B8%84%E0%B8%A7%E0%B8%A3%E0%B9%81%E0%B8%97%E0%B8%99%E0%B8%97%E0%B8%B5%E0%B9%88-parent-%E0%B9%84%E0%B8%94%E0%B9%89%E0%B8%88%E0%B8%A3%E0%B8%B4%E0%B8%87-c7a9b508f850">Liskov Substitution Principle (LSP)</a></li><li><a href="https://medium.com/@gdunghi/interface-segregation-principle-isp-1876c6388962">Interface Segregation Principle (ISP)</a></li><li><a href="https://medium.com/@gdunghi/dependency-inversion-principle-dip-c1df5c344592">Dependency Inversion Principle (DIP)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed66d0bc0574" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Single Responsibility Principle (SRP) (SOLID Principle)]]></title>
            <link>https://medium.com/@gdunghi/single-responsibility-principle-srp-solid-principle-b8d9e9962ab4?source=rss-4570570b2ddb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8d9e9962ab4</guid>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[rp]]></category>
            <dc:creator><![CDATA[Jirayu Photisan]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 09:12:22 GMT</pubDate>
            <atom:updated>2026-08-25T02:26:50.115Z</atom:updated>
            <content:encoded><![CDATA[<h3>Single Responsibility Principle (SRP)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9PS5aFrdRnuJehuWF8W1-w.png" /></figure><p>จาก <strong>SOLID Principles</strong></p><pre>S = Single Responsibility<br>    หนึ่ง class มีหนึ่ง responsibility<br><br>O = Open/Closed<br>    เพิ่มความสามารถโดยไม่ต้องแก้ของเดิม<br><br>L = Liskov Substitution<br>    ลูกต้องแทนพ่อได้โดยไม่ทำให้ระบบพัง<br><br>I = Interface Segregation<br>    อย่าบังคับให้ client depend กับสิ่งที่ไม่ใช้<br><br>D = Dependency Inversion<br>    พึ่ง abstraction ไม่พึ่ง implementation</pre><p>เมื่อพูดถึง <strong>SOLID Principles</strong> หลักแรกที่เรามักได้ยินคือ</p><blockquote><strong><em>S — Single Responsibility Principle</em></strong></blockquote><p>และประโยคที่คนส่วนใหญ่มักจำได้คือ:</p><blockquote><strong><em>“A class should have only one responsibility.”</em></strong></blockquote><p>ฟังดูเข้าใจง่ายมาก</p><p>แต่เมื่อเริ่มเขียนระบบจริง เราจะพบคำถามทันทีว่า</p><ul><li>แล้ว “หนึ่ง Responsibility” คืออะไร?</li><li>Class ที่มี 10 methods ผิด SRP หรือไม่?</li><li>Service ที่มีหลาย method แต่เกี่ยวข้องกับ User ผิดหรือเปล่า?</li><li>Controller ควรมีแค่ method เดียวหรือไม่?</li><li>เราควรแยก Class ให้เล็กที่สุดหรือไม่?</li></ul><p>จริง ๆ แล้ว SRP ไม่ได้หมายความว่า</p><blockquote><strong><em>หนึ่ง Class ต้องมีเพียงหนึ่ง Method</em></strong></blockquote><p>และไม่ได้หมายความว่า</p><blockquote><strong><em>หนึ่ง Class ต้องทำงานเพียงหนึ่งอย่างแบบเล็ก ๆ</em></strong></blockquote><p>ความหมายที่สำคัญกว่าคือ:</p><blockquote><strong><em>A class should have one reason to change.</em></strong></blockquote><p>หรือ</p><blockquote><strong><em>หนึ่ง Class ควรมีเหตุผลหลักเพียงหนึ่งเหตุผลที่ทำให้ต้องเปลี่ยน</em></strong></blockquote><p>แนวคิดนี้ทำให้เราเข้าใจ SRP ได้ถูกต้องมากขึ้น</p><h3>ปัญหาของ Class ที่มีหลาย Responsibility</h3><p>ลองดูตัวอย่างระบบ Order</p><pre>public class OrderService {<br>    public void createOrder(Order order) {<br>        // Create order<br>    }<br>    public void calculatePrice(Order order) {<br>        // Calculate price<br>    }<br>    public void sendEmail(Order order) {<br>        // Send email<br>    }<br>    public void generateInvoice(Order order) {<br>        // Generate PDF<br>    }<br>    public void saveToDatabase(Order order) {<br>        // Save to database<br>    }<br>}</pre><p>มองครั้งแรกอาจรู้สึกว่า</p><blockquote><em>“ก็เป็น OrderService นี่ ทุกอย่างเกี่ยวกับ Order ก็อยู่ที่นี่สิ”</em></blockquote><p>แต่ลองดู Responsibility จริง ๆ</p><pre>OrderService<br>│<br>├── Business Rule<br>│   └── Calculate Price<br>│<br>├── Database<br>│   └── Save Order<br>│<br>├── Email<br>│   └── Send Email<br>│<br>└── Document<br>    └── Generate Invoice</pre><p>Class เดียวกำลังรับผิดชอบหลายเรื่อง</p><p>และแต่ละเรื่องมี <strong>เหตุผลที่ทำให้ต้องเปลี่ยนไม่เหมือนกัน</strong></p><h3>Reason to Change คืออะไร?</h3><p>สมมติวันหนึ่งฝ่ายบัญชีบอกว่า:</p><blockquote><em>“รูปแบบ Invoice ต้องเปลี่ยน”</em></blockquote><p>เราต้องแก้:</p><pre>generateInvoice()</pre><p>แต่ถ้าฝ่าย Infrastructure เปลี่ยน Database:</p><pre>MySQL → PostgreSQL</pre><p>เราต้องแก้:</p><pre>saveToDatabase()</pre><p>ถ้าฝ่าย Marketing ต้องการเปลี่ยน Email Template:</p><pre>sendEmail()</pre><p>ก็ต้องแก้อีก</p><p>และถ้า Business เปลี่ยนวิธีคำนวณราคา:</p><pre>calculatePrice()</pre><p>ก็ต้องแก้อีก</p><p>ดังนั้น OrderService มีหลายเหตุผลที่ทำให้ต้องเปลี่ยน</p><pre>Business Rule Change<br>        ↓<br>   OrderService<br>        ↑<br>Database Change<br>        ↑<br>Email Change<br>        ↑<br>Invoice Change</pre><p>นี่คือสัญญาณว่า Class นี้มีหลาย Responsibility</p><h3>SRP ไม่ได้หมายความว่า “หนึ่ง Class = หนึ่ง Method”</h3><p>นี่เป็นความเข้าใจผิดที่พบบ่อยมาก</p><p>สมมติเรามี:</p><pre>public class OrderCalculator {<br>    public Money calculateSubtotal(Order order) {<br>        // ...<br>    }<br>    public Money calculateDiscount(Order order) {<br>        // ...<br>    }<br>    public Money calculateTax(Order order) {<br>        // ...<br>    }<br>    public Money calculateTotal(Order order) {<br>        // ...<br>    }<br>}</pre><p>Class นี้มีหลาย Method</p><p>แต่ทั้งหมดเกี่ยวข้องกับ:</p><blockquote><strong><em>การคำนวณราคา Order</em></strong></blockquote><p>ดังนั้น Class นี้อาจมี <strong>หนึ่ง Responsibility</strong> แม้ว่าจะมีหลาย Method</p><pre>OrderCalculator<br>│<br>├── calculateSubtotal()<br>├── calculateDiscount()<br>├── calculateTax()<br>└── calculateTotal()</pre><p>ทั้งหมดเปลี่ยนด้วยเหตุผลเดียวกัน:</p><blockquote><strong><em>กฎการคำนวณราคาเปลี่ยน</em></strong></blockquote><p>ดังนั้นไม่จำเป็นต้องแยกทุก Method ออกเป็น Class ของตัวเอง</p><h3>SRP ที่ดีคือ Cohesion</h3><p>สิ่งที่ SRP ต้องการจริง ๆ คือ <strong>High Cohesion</strong></p><p>พูดง่าย ๆ คือ:</p><blockquote><em>สิ่งที่อยู่ใน Class เดียวกันควรมีความเกี่ยวข้องกัน</em></blockquote><p>ตัวอย่าง:</p><pre>public class OrderCalculator {<br>    public Money calculateSubtotal(Order order) {<br>        // ...<br>    }<br>    public Money calculateDiscount(Order order) {<br>        // ...<br>    }<br>    public Money calculateTax(Order order) {<br>        // ...<br>    }<br>    public Money calculateTotal(Order order) {<br>        // ...<br>    }<br>}</pre><p>ทุก Method มีความสัมพันธ์กันสูง</p><p>แต่ถ้าเป็น:</p><pre>public class OrderService {<br>    public void calculatePrice() {}<br>    public void sendEmail() {}<br>    public void exportExcel() {}<br>    public void saveToDatabase() {}<br>    public void uploadToS3() {}<br>}</pre><p>ความสัมพันธ์น้อยมาก</p><p>นี่เป็นสัญญาณว่า Class กำลังรวมหลาย Responsibility เข้าด้วยกัน</p><h3>Refactor ตาม SRP</h3><p>เราสามารถแยก Class ออกตาม Responsibility</p><p>จากเดิม:</p><pre>OrderService<br>├── Calculate Price<br>├── Save Database<br>├── Send Email<br>└── Generate Invoice</pre><p>เปลี่ยนเป็น:</p><pre>OrderService<br>OrderCalculator<br>OrderRepository<br>OrderNotification<br>InvoiceGenerator</pre><p>ตัวอย่าง:</p><pre>public class OrderCalculator {<br>    public Money calculateTotal(Order order) {<br>        // Business rules<br>        return Money.zero();<br>    }<br>}</pre><p>Repository:</p><pre>public interface OrderRepository {<br>   void save(Order order);<br>}</pre><p>Notification:</p><pre>public interface OrderNotification {<br>    void sendOrderCreated(Order order);<br>}</pre><p>Invoice:</p><pre>public interface InvoiceGenerator {<br>    byte[] generate(Order order);<br>}</pre><p>ตอนนี้แต่ละ Class มี Responsibility ที่ชัดขึ้น</p><pre>OrderCalculator<br>    ↓<br>Price calculation<br>    <br>OrderRepository<br>    ↓<br>Persistence<br>     <br>OrderNotification<br>    ↓<br>Notification<br>    <br>InvoiceGenerator<br>    ↓<br>Invoice generation</pre><h3>แล้ว OrderService หายไปหรือไม่?</h3><p>ไม่จำเป็นต้องหาย</p><p>เรายังสามารถมี OrderService เป็น <strong>Orchestrator </strong>ได้</p><pre>public class OrderService {<br>    private final OrderCalculator calculator;<br>    private final OrderRepository repository;<br>    private final OrderNotification notification;<br>    public OrderService(<br>            OrderCalculator calculator,<br>            OrderRepository repository,<br>            OrderNotification notification) {<br>        this.calculator = calculator;<br>        this.repository = repository;<br>        this.notification = notification;<br>    }<br>    public void createOrder(Order order) {<br>        Money total =<br>                calculator.calculateTotal(order);<br>        order.setTotal(total);<br>        repository.save(order);<br>        notification.sendOrderCreated(order);<br>    }<br>}</pre><p>สิ่งที่เปลี่ยนคือ OrderService ไม่ได้ทำทุกอย่างเองแล้ว</p><p>มันทำหน้าที่เป็น <strong>Orchestrator</strong></p><pre>                 OrderService<br>                      │<br>        ┌─────────────┼─────────────┐<br>        │             │             │<br>        ▼             ▼             ▼<br>   Calculator     Repository    Notification<br>        │             │             │<br>     Business       Database       Email<br>       Rule</pre><p>นี่เป็นรูปแบบที่พบได้บ่อยใน Application Service / Use Case</p><p>อีกตัวอย่างที่พบได้บ่อย:</p><pre>public class OrderService {<br>    public void createOrder(Order order) {<br>        validate(order);<br>        calculatePrice(order);<br>        jdbcTemplate.update(<br>            &quot;INSERT INTO orders ...&quot;<br>        );<br>        sendEmail(order);<br>    }<br>}</pre><p>Class นี้รู้จักทั้ง:</p><pre>Business Rule<br>JDBC<br>SQL<br>Email</pre><p>ถ้าใช้แนวคิด SRP เราสามารถแยก:</p><pre>public interface OrderRepository {<br>    void save(Order order);<br>}</pre><p>และ:</p><pre>public interface OrderNotification {<br>    void send(Order order);<br>}</pre><p>จากนั้น:</p><pre>public class OrderService {<br>    private final OrderRepository repository;<br>    private final OrderNotification notification;<br>    public void createOrder(Order order) {<br>        validate(order);<br>        calculatePrice(order);<br>        repository.save(order);<br>        notification.send(order);<br>    }<br>}</pre><p>OrderService จึงเน้นที่ <strong>Use Case / Business Flow</strong></p><p>ไม่ได้ลงไปจัดการรายละเอียดของ Database หรือ Email เอง</p><h3>SRP ไม่ใช่การแยก Class ให้เล็กที่สุด</h3><p>นี่เป็นอีกเรื่องที่สำคัญมาก</p><p>บางครั้ง Developer เข้าใจ SRP ว่า:</p><blockquote><em>“Class ใหญ่ = ผิด”</em></blockquote><p>แล้วเริ่มแยกทุกอย่าง</p><p>จาก:</p><pre>OrderCalculator</pre><p>กลายเป็น:</p><pre>SubtotalCalculator<br>DiscountCalculator<br>TaxCalculator<br>ShippingCalculator<br>TotalCalculator</pre><p>จนระบบกลายเป็น:</p><pre>OrderService<br>   ↓<br>SubtotalCalculator<br>   ↓<br>DiscountCalculator<br>   ↓<br>TaxCalculator<br>   ↓<br>ShippingCalculator<br>   ↓<br>TotalCalculator</pre><p>สุดท้ายการอ่าน Code ยากกว่าเดิม</p><p>นี่เรียกว่า <strong>Over-engineering</strong></p><p>SRP ไม่ได้บอกว่า:</p><blockquote><em>“ทำ Class ให้เล็กที่สุด”</em></blockquote><p>แต่บอกว่า:</p><blockquote><strong><em>“จัด Responsibility ให้มี Cohesion และมีเหตุผลในการเปลี่ยนที่ชัดเจน”</em></strong></blockquote><h3>วิธีหา Responsibility ของ Class</h3><p>เวลาสงสัยว่า Class ผิด SRP หรือไม่ ลองถามคำถามนี้:</p><blockquote><strong><em>“มีใครบ้างที่สามารถมาขอให้เราแก้ Class นี้?”</em></strong></blockquote><p>ตัวอย่าง:</p><pre>OrderService</pre><p>ถ้าเราตอบได้ว่า:</p><pre>ฝ่าย Business<br>ฝ่าย Database<br>ฝ่าย Marketing<br>ฝ่ายบัญชี<br>ฝ่าย Infrastructure</pre><p>อาจเป็นสัญญาณว่า Class นี้มีหลาย Responsibility</p><p>แต่ถ้า:</p><pre>Order Pricing Team</pre><p>เป็นคนเดียวที่มีเหตุผลหลักในการเปลี่ยน Class:</p><pre>OrderCalculator</pre><p>ก็มีแนวโน้มว่า Responsibility ชัดเจนกว่า</p><h3>สัญญาณว่า Class อาจผิด SRP</h3><p>ลองสังเกต Code Smells เหล่านี้:</p><h3>1. Class มี Dependency จำนวนมาก</h3><pre>class OrderService {</pre><pre>    JdbcTemplate jdbc;<br>    EmailClient email;<br>    S3Client s3;<br>    PdfGenerator pdf;<br>    PaymentClient payment;<br>    RedisClient redis;<br>}</pre><p>อาจเป็นสัญญาณว่า Class รู้เรื่องมากเกินไป</p><h3>2. Method อยู่คนละกลุ่มกัน</h3><pre>createOrder()<br>calculatePrice()<br>sendEmail()<br>uploadFile()<br>generatePdf()<br>saveDatabase()</pre><p>ถ้า Method แต่ละกลุ่มมีเหตุผลในการเปลี่ยนต่างกัน อาจต้องแยก Responsibility</p><h3>3. Class ถูกแก้บ่อยจากหลายสาเหตุ</h3><p>ถ้า Git History แสดงว่า Class เดียวถูกแก้เพราะ:</p><pre>Business Change<br>Database Change<br>Email Change<br>API Change<br>Report Change</pre><p>นี่เป็นสัญญาณที่ดีมากว่า Class อาจมีหลาย Responsibility</p><h3>4. Unit Test ใหญ่และซับซ้อน</h3><p>ถ้าการ Test OrderService ต้อง Mock:</p><pre>Database<br>Email<br>Redis<br>Kafka<br>S3<br>Payment API</pre><p>พร้อมกันจำนวนมาก</p><p>อาจเป็นสัญญาณว่า Class นี้มีหน้าที่มากเกินไป</p><h3>อย่าใช้ SRP แบบ Mechanical</h3><p>สิ่งสำคัญที่สุดคือ:</p><blockquote><strong><em>SOLID ไม่ใช่กฎที่ต้องทำตามแบบ Mechanical</em></strong></blockquote><p>เราไม่ควรเห็น Class มี 10 Methods แล้วรีบแยก</p><p>หรือเห็น Class มี 500 Lines แล้วสรุปทันทีว่าผิด SRP</p><p>ให้ดูว่า:</p><pre>Methods เหล่านั้นเกี่ยวข้องกันหรือไม่?<br>        ↓<br>มี Cohesion หรือไม่?<br>        ↓<br>มี Reason to Change เดียวกันหรือไม่?<br>        ↓<br>มี Actor เดียวกันหรือไม่?<br>        ↓<br>ถ้าเปลี่ยนเรื่องหนึ่ง<br>เรื่องอื่นควรต้องเปลี่ยนด้วยหรือไม่?</pre><p>ถ้าคำตอบคือ “ใช่” หลายข้อ Class นั้นอาจมี Responsibility ที่เหมาะสมแล้ว</p><h3>สรุป SRP</h3><p>SRP ไม่ใช่:</p><pre>One Class = One Method<br><br>One Class = One Function<br><br>Class ต้องเล็กที่สุด<br><br>ทุกอย่างต้องแยกเป็น Interface</pre><p>แต่คือ:</p><pre>One Responsibility<br><br>One Cohesive Purpose<br><br>One Primary Reason to Change</pre><p>ดังนั้นเมื่อออกแบบ Class ให้ลองถามว่า:</p><blockquote><strong><em>Class นี้มีหน้าที่อะไร?</em></strong></blockquote><p>แต่คำถามที่ดีกว่าคือ:</p><blockquote><strong><em>อะไรคือเหตุผลที่ทำให้ Class นี้ต้องเปลี่ยน?</em></strong></blockquote><p>ถ้าคำตอบมีหลายเรื่อง เช่น:</p><pre>Business Rule<br>Database<br>Email<br>Reporting<br>API</pre><p>อาจถึงเวลาที่ต้องแยก Responsibility</p><p>แต่ถ้าทุก Method มีเหตุผลในการเปลี่ยนร่วมกัน แม้จะมีหลาย Method อยู่ใน Class เดียว ก็ไม่ได้หมายความว่า Class นั้นผิด SRP</p><h3>Final Thought</h3><p>SRP เป็น Principle ที่ดูเหมือนง่ายที่สุดใน SOLID แต่ในทางปฏิบัติกลับเป็นหนึ่งในหลักที่ตีความผิดได้ง่ายที่สุด</p><p>เพราะคำว่า <strong>Single Responsibility</strong> ไม่ได้หมายถึง “ทำเพียงสิ่งเดียว”</p><p>แต่หมายถึง:</p><blockquote><strong><em>“มีเหตุผลหลักเพียงหนึ่งเหตุผลที่ทำให้ต้องเปลี่ยน”</em></strong></blockquote><p>เมื่อเราออกแบบโดยคิดถึง <strong>Responsibility, Cohesion และ Reason to Change</strong> เราจะไม่ได้แค่เขียน Class ที่เล็กลง แต่จะสร้างระบบที่แต่ละส่วนมีขอบเขตชัดเจน และการเปลี่ยนแปลงในส่วนหนึ่งจะไม่ลากผลกระทบไปยังส่วนอื่นโดยไม่จำเป็น</p><p>และเมื่อ SRP ถูกนำมาใช้ร่วมกับหลักอื่นใน SOLID เช่น <strong>OCP, LSP, ISP และ DIP</strong> เราจะเริ่มเห็นภาพว่า SOLID ไม่ได้เป็นเพียงกฎสำหรับเขียน Class แต่เป็นแนวคิดสำหรับออกแบบ Software ที่สามารถเปลี่ยนแปลงและดูแลรักษาได้ในระยะยาว</p><p>ถึงตรงนี้แล้วไปกันต่อที่หัวข้อถัดไป <a href="https://medium.com/@gdunghi/open-closed-principle-ocp-%E0%B9%80%E0%B8%82%E0%B8%B5%E0%B8%A2%E0%B8%99-code-%E0%B8%A2%E0%B8%B1%E0%B8%87%E0%B9%84%E0%B8%87%E0%B9%83%E0%B8%AB%E0%B9%89%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B1%E0%B8%9A%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%80%E0%B8%9B%E0%B8%A5%E0%B8%B5%E0%B9%88%E0%B8%A2%E0%B8%99%E0%B9%81%E0%B8%9B%E0%B8%A5%E0%B8%87-ed66d0bc0574">Open/Closed Principle (OCP)</a></p><blockquote>Happy coding</blockquote><blockquote><strong><em>หมายเหตุ:</em></strong><em> บทความนี้เรียบเรียงและปรับภาษาโดยใช้ ChatGPT ช่วย โดยเนื้อหา แนวคิด และตัวอย่างมาจากผู้เขียน</em></blockquote><h3>SOLID Principles</h3><ul><li><a href="https://medium.com/@gdunghi/single-responsibility-principle-srp-solid-principle-b8d9e9962ab4">Single Responsibility Principle (SRP)</a></li><li><a href="https://medium.com/@gdunghi/open-closed-principle-ocp-%E0%B9%80%E0%B8%82%E0%B8%B5%E0%B8%A2%E0%B8%99-code-%E0%B8%A2%E0%B8%B1%E0%B8%87%E0%B9%84%E0%B8%87%E0%B9%83%E0%B8%AB%E0%B9%89%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B1%E0%B8%9A%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%80%E0%B8%9B%E0%B8%A5%E0%B8%B5%E0%B9%88%E0%B8%A2%E0%B8%99%E0%B9%81%E0%B8%9B%E0%B8%A5%E0%B8%87-ed66d0bc0574">Open/Closed Principle (OCP)</a></li><li><a href="https://medium.com/@gdunghi/liskov-substitution-principle-lsp-%E0%B9%80%E0%B8%A1%E0%B8%B7%E0%B9%88%E0%B8%AD-subclass-%E0%B8%84%E0%B8%A7%E0%B8%A3%E0%B9%81%E0%B8%97%E0%B8%99%E0%B8%97%E0%B8%B5%E0%B9%88-parent-%E0%B9%84%E0%B8%94%E0%B9%89%E0%B8%88%E0%B8%A3%E0%B8%B4%E0%B8%87-c7a9b508f850">Liskov Substitution Principle (LSP)</a></li><li><a href="https://medium.com/@gdunghi/interface-segregation-principle-isp-1876c6388962">Interface Segregation Principle (ISP)</a></li><li><a href="https://medium.com/@gdunghi/dependency-inversion-principle-dip-c1df5c344592">Dependency Inversion Principle (DIP)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8d9e9962ab4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[สรุป 3 หมวดหมู่หลักของ Design Patterns แบบเข้าใจง่าย]]></title>
            <link>https://medium.com/@gdunghi/%E0%B8%AA%E0%B8%A3%E0%B8%B8%E0%B8%9B-3-%E0%B8%AB%E0%B8%A1%E0%B8%A7%E0%B8%94%E0%B8%AB%E0%B8%A1%E0%B8%B9%E0%B9%88%E0%B8%AB%E0%B8%A5%E0%B8%B1%E0%B8%81%E0%B8%82%E0%B8%AD%E0%B8%87-design-patterns-%E0%B9%81%E0%B8%9A%E0%B8%9A%E0%B9%80%E0%B8%82%E0%B9%89%E0%B8%B2%E0%B9%83%E0%B8%88%E0%B8%87%E0%B9%88%E0%B8%B2%E0%B8%A2-a1ced201230d?source=rss-4570570b2ddb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1ced201230d</guid>
            <category><![CDATA[strategy-pattern]]></category>
            <category><![CDATA[adapter-pattern]]></category>
            <category><![CDATA[decorator-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[proxy-pattern]]></category>
            <dc:creator><![CDATA[Jirayu Photisan]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 09:15:24 GMT</pubDate>
            <atom:updated>2026-08-02T09:23:50.287Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iIkEQgAJza1e0kNpBn_EiQ.png" /></figure><p>ในการพัฒนาซอฟต์แวร์ <strong>Design Patterns</strong> คือรูปแบบหรือแนวทางปฏิบัติที่เป็นมาตรฐานในการแก้ปัญหาที่เกิดขึ้นบ่อย ๆ ในการออกแบบโค้ด ซึ่งรูปแบบเหล่านี้สามารถแบ่งออกได้เป็น 3 หมวดหมู่หลัก ดังนี้ครับ</p><h3>A — Creational Patterns (รูปแบบการสร้างออบเจกต์)</h3><p>หมวดหมู่นี้จะจัดการกับ <strong>กลไกการสร้าง Object</strong> เพื่อลดการพึ่งพากัน (Decouple) ระหว่างโค้ดส่วนที่เรียกใช้งาน (Client) กับคลาสที่นำไปสร้างจริง (Concrete Classes) ทำให้ระบบยืดหยุ่นและดูแลรักษาง่ายขึ้น</p><h4>1. Factory Pattern</h4><p>รวมลอจิกการสร้าง Object ไว้ที่จุดเดียว และคืนค่า (Return) Subclass ที่แตกต่างกันออกไปตาม Input ที่ได้รับมา</p><pre>interface Notification {<br>  send(message: string): void;<br>}<br><br>class EmailNotification implements Notification {<br>  send(message: string) { console.log(`ส่ง Email: ${message}`); }<br>}<br><br>class SMSNotification implements Notification {<br>  send(message: string) { console.log(`ส่ง SMS: ${message}`); }<br>}<br><br>// Factory Class<br>class NotificationFactory {<br>  static createNotification(type: &#39;email&#39; | &#39;sms&#39;): Notification {<br>    if (type === &#39;email&#39;) return new EmailNotification();<br>    if (type === &#39;sms&#39;) return new SMSNotification();<br>    throw new Error(&#39;ไม่รองรับประเภทการแจ้งเตือนนี้&#39;);<br>  }<br>}<br><br>// การเรียกใช้งาน (Client)<br>const myNotifier = NotificationFactory.createNotification(&#39;email&#39;);<br>myNotifier.send(&quot;สวัสดีจาก Factory Pattern!&quot;);</pre><h4>2. Singleton Pattern</h4><p>ควบคุมให้คลาสนั้น ๆ มี Instance เกิดขึ้นเพียง <strong>ตัวเดียวเท่านั้น</strong> ในระบบ เช่น การเชื่อมต่อ Database</p><pre>class DatabaseConnection {<br>  private static instance: DatabaseConnection;<br><br>  // private constructor ป้องกันไม่ให้ใช้คำสั่ง new จากภายนอก<br>  private constructor() {<br>    console.log(&quot;เชื่อมต่อฐานข้อมูลครั้งแรกและครั้งเดียว!&quot;);<br>  }<br><br>  static getInstance(): DatabaseConnection {<br>    if (!DatabaseConnection.instance) {<br>      DatabaseConnection.instance = new DatabaseConnection();<br>    }<br>    return DatabaseConnection.instance;<br>  }<br><br>  query(sql: string) { console.log(`กำลังรัน: ${sql}`); }<br>}<br><br>// การเรียกใช้งาน<br>const db1 = DatabaseConnection.getInstance();<br>const db2 = DatabaseConnection.getInstance();<br>console.log(db1 === db2); // ผลลัพธ์: true (เป็น Object ตัวเดียวกัน)</pre><h4>3. Builder Pattern</h4><p>ช่วยสร้าง Object ที่มีความซับซ้อนแบบเป็นขั้นเป็นตอน ทำให้เลือกตั้งค่าเฉพาะส่วนที่ต้องการได้โดยไม่ต้องพึ่งพา Constructor ที่ยาวเหยียด</p><pre>class Burger {<br>  cheese: boolean = false;<br>  bacon: boolean = false;<br>  lettuce: boolean = false;<br>}<br><br>class BurgerBuilder {<br>  private burger = new Burger();<br><br>  addCheese() { this.burger.cheese = true; return this; }<br>  addBacon() { this.burger.bacon = true; return this; }<br>  addLettuce() { this.burger.lettuce = true; return this; }<br>  <br>  build(): Burger { return this.burger; }<br>}<br><br>// การเรียกใช้งาน<br>const myBurger = new BurgerBuilder().addCheese().addBacon().build();<br>console.log(myBurger); // { cheese: true, bacon: true, lettuce: false }</pre><h3>B — Structural Patterns (รูปแบบโครงสร้าง)</h3><p>หมวดหมู่นี้จะช่วยในการ <strong>ประกอบคลาสและ Object ต่าง ๆ</strong> เข้าด้วยกัน เพื่อสร้างเป็นโครงสร้างของระบบที่ใหญ่ขึ้นและทำงานร่วมกันได้อย่างมีประสิทธิภาพ</p><h3>1. Adapter Pattern</h3><p>ทำให้ Interface ที่แต่เดิมเข้ากันไม่ได้ สามารถทำงานร่วมกันได้ (เหมือนหัวแปลงปลั๊กไฟ)</p><pre>// Interface ระบบใหม่ที่โปรแกรมเราคาดหวัง<br>interface NewPaymentProcessor {<br>  pay(amount: number): void;<br>}<br><br>// ระบบเก่า (Incompatible Interface)<br>class OldPaymentSystem {<br>  makePayment(money: number, currency: string) {<br>    console.log(`ชำระเงิน ${money} ${currency} ผ่านระบบเก่า`);<br>  }<br>}<br><br>// Adapter ที่ทำหน้าที่เป็นตัวแปลง<br>class PaymentAdapter implements NewPaymentProcessor {<br>  constructor(private oldSystem: OldPaymentSystem) {}<br><br>  pay(amount: number): void {<br>    // แปลงรูปแบบใหม่ให้เข้ากับระบบเก่า<br>    this.oldSystem.makePayment(amount, &quot;THB&quot;);<br>  }<br>}<br><br>// การเรียกใช้งาน<br>const adapter = new PaymentAdapter(new OldPaymentSystem());<br>adapter.pay(500); // ใช้งานแบบใหม่ แต่ข้างในไปเรียกใช้ระบบเก่า</pre><h4>2. Decorator Pattern</h4><p>เพิ่มความสามารถใหม่ ๆ ให้กับ Object ได้แบบ Dynamic โดยไม่ต้องแก้ไขโครงสร้างโค้ดเดิม</p><pre>interface Coffee {<br>  cost(): number;<br>  description(): string;<br>}<br><br>class BasicCoffee implements Coffee {<br>  cost() { return 50; }<br>  description() { return &quot;กาแฟดำ&quot;; }<br>}<br><br>// Decorator สำหรับการเพิ่มนม<br>class MilkDecorator implements Coffee {<br>  constructor(private coffee: Coffee) {}<br>  cost() { return this.coffee.cost() + 15; }<br>  description() { return this.coffee.description() + &quot; + นม&quot;; }<br>}<br><br>// การเรียกใช้งาน<br>let myCoffee: Coffee = new BasicCoffee();<br>myCoffee = new MilkDecorator(myCoffee); // เติมนมเพิ่มเข้าไป<br><br>console.log(`${myCoffee.description()} ราคา: ${myCoffee.cost()} บาท`);</pre><h4>3. Proxy Pattern</h4><p>ทำหน้าที่เป็นตัวแทน (Placeholder) ในการควบคุมหรือคัดกรองการเข้าถึง Object อื่นที่อยู่เบื้องหลัง</p><pre>interface Document { read(): void; }<br><br>class SecretDocument implements Document {<br>  read() { console.log(&quot;เนื้อหา: แผนลับสุดยอด!&quot;); }<br>}<br><br>class SecurityProxy implements Document {<br>  private secretDoc = new SecretDocument();<br>  constructor(private role: string) {}<br><br>  read() {<br>    if (this.role === &quot;ADMIN&quot;) this.secretDoc.read();<br>    else console.log(&quot;Access Denied: คุณไม่มีสิทธิ์เข้าถึง&quot;);<br>  }<br>}<br><br>// การเรียกใช้งาน<br>const userProxy = new SecurityProxy(&quot;GUEST&quot;);<br>userProxy.read(); // Access Denied<br><br>const adminProxy = new SecurityProxy(&quot;ADMIN&quot;);<br>adminProxy.read(); // เข้าถึงได้</pre><h3>C — Behavioral Patterns (รูปแบบพฤติกรรม)</h3><p>หมวดหมู่นี้จะเน้นไปที่ <strong>การสื่อสารและการโต้ตอบกัน</strong> ระหว่าง Object ต่าง ๆ ว่าจะแบ่งหน้าที่และส่งข้อมูลหากันอย่างไรให้เป็นระบบ</p><h4>1. Strategy Pattern</h4><p>ช่วยให้เราเลือกใช้ <strong>รูปแบบการทำงาน (Algorithms)</strong> ที่เตรียมไว้หลาย ๆ แบบ และสามารถสลับสับเปลี่ยนกันได้ทันทีขณะโปรแกรมทำงาน (Runtime)</p><pre>interface PaymentStrategy {<br>  pay(amount: number): void;<br>}<br><br>class CreditCardPayment implements PaymentStrategy {<br>  pay(amount: number) { console.log(`จ่าย ${amount} บาท ด้วยบัตรเครดิต`); }<br>}<br>class PromptPayPayment implements PaymentStrategy {<br>  pay(amount: number) { console.log(`จ่าย ${amount} บาท ด้วยพร้อมเพย์`); }<br>}<br><br>// Context<br>class ShoppingCart {<br>  constructor(private strategy: PaymentStrategy) {}<br>  setStrategy(strategy: PaymentStrategy) { this.strategy = strategy; }<br>  checkout(amount: number) { this.strategy.pay(amount); }<br>}<br><br>// การเรียกใช้งาน<br>const cart = new ShoppingCart(new CreditCardPayment());<br>cart.checkout(1000); // จ่ายด้วยบัตร<br><br>cart.setStrategy(new PromptPayPayment()); // สลับวิธีจ่ายเงิน<br>cart.checkout(500); // จ่ายด้วยพร้อมเพย์</pre><h4>2. Observer Pattern</h4><p>สร้าง <strong>การเชื่อมโยง</strong> แบบ One-to-Many เมื่อ Object หลักมีการเปลี่ยนแปลงสถานะ Object อื่น ๆ ที่ติดตามอยู่จะได้รับการแจ้งเตือนอัตโนมัติ</p><pre>interface Observer {<br>  update(status: string): void;<br>}<br><br>class Customer implements Observer {<br>  constructor(private name: string) {}<br>  update(status: string) { console.log(`คุณ ${this.name}: สินค้าของคุณสถานะคือ ${status}`); }<br>}<br><br>class OrderSubject {<br>  private observers: Observer[] = [];<br>  private status: string = &quot;รอดำเนินการ&quot;;<br><br>  subscribe(observer: Observer) { this.observers.push(observer); }<br>  <br>  setStatus(newStatus: string) {<br>    this.status = newStatus;<br>    this.observers.forEach(obs =&gt; obs.update(this.status));<br>  }<br>}<br><br>// การเรียกใช้งาน<br>const order = new OrderSubject();<br>order.subscribe(new Customer(&quot;A&quot;));<br>order.subscribe(new Customer(&quot;B&quot;));<br><br>order.setStatus(&quot;กำลังจัดส่ง&quot;); // A และ B ได้รับแจ้งเตือนพร้อมกัน</pre><h4>3. Command Pattern</h4><p>รูปแบบการออกแบบโค้ด (Behavioral Design Pattern) ที่แปลงคำสั่งหรือการขอให้ทำสิ่งใดสิ่งหนึ่งให้กลายเป็น Object อิสระ ทำให้เราสามารถเก็บคำสั่ง ส่งต่อ หรือนำคำสั่งนั้นไปสั่งทำงานย้อนหลัง (Undo/Redo) หรือเข้าคิวรอทำงาน (Queue) ได้อย่างสะดวก</p><pre>// 1. Command Interface: กำหนดหน้าตาของคำสั่งว่าต้องทำอะไรได้บ้าง<br>// (สิ่งสำคัญคือต้องมี execute สำหรับทำงาน และ undo สำหรับยกเลิกการทำงาน)<br>interface Command {<br>  execute(): void;<br>  undo(): void; <br>}<br><br>// 2. Receiver: ตัวทำงานจริง (ในที่นี้คือเครื่องคิดเลข)<br>class Calculator {<br>  private currentValue: number = 0;<br>  <br>  add(value: number) { this.currentValue += value; }<br>  subtract(value: number) { this.currentValue -= value; }<br>  <br>  getValue() { return this.currentValue; }<br>}<br><br>// 3. Concrete Commands: นำคำสั่งมาปั้นเป็น Object <br>// อัดข้อมูลที่จำเป็น (เช่น ตัวเลขที่ต้องการบวก/ลบ) เก็บไว้ในตัวมันเอง<br>class AddCommand implements Command {<br>  // รับเครื่องคิดเลข และตัวเลขที่ต้องการบวกเข้ามาเก็บไว้<br>  constructor(private calculator: Calculator, private value: number) {}<br><br>  execute() { this.calculator.add(this.value); }<br>  undo() { this.calculator.subtract(this.value); } // Undo ของบวก คือการลบออก<br>}<br><br>class SubtractCommand implements Command {<br>  constructor(private calculator: Calculator, private value: number) {}<br><br>  execute() { this.calculator.subtract(this.value); }<br>  undo() { this.calculator.add(this.value); } // Undo ของลบ คือการบวกกลับ<br>}<br><br>// 4. Invoker: แอปพลิเคชันหรือคนกดปุ่ม ที่คอยเรียกใช้คำสั่งและจำประวัติ<br>class CalculatorApp {<br>  private history: Command[] = []; // เก็บประวัติคำสั่งไว้เป็น Array<br><br>  executeCommand(command: Command) {<br>    command.execute();           // รันคำสั่ง<br>    this.history.push(command);  // เก็บคำสั่งนี้ลงประวัติ<br>  }<br><br>  undo() {<br>    const lastCommand = this.history.pop(); // ดึงคำสั่งล่าสุดออกมา<br>    if (lastCommand) {<br>      lastCommand.undo(); // สั่งให้ Object นั้นทำการย้อนกลับการกระทำของตัวมันเอง<br>    } else {<br>      console.log(&quot;ไม่มีประวัติให้ Undo แล้วครับ&quot;);<br>    }<br>  }<br>}<br><br>// ==========================================<br>// การเรียกใช้งาน (Client)<br>// ==========================================<br><br>const myCalc = new Calculator();<br>const app = new CalculatorApp();<br><br>console.log(`ค่าเริ่มต้น: ${myCalc.getValue()}`); // 0<br><br>// สั่งบวก 10<br>app.executeCommand(new AddCommand(myCalc, 10));<br>console.log(`บวก 10 -&gt; ผลลัพธ์: ${myCalc.getValue()}`); // 10<br><br>// สั่งบวก 5<br>app.executeCommand(new AddCommand(myCalc, 5));<br>console.log(`บวก 5 -&gt; ผลลัพธ์: ${myCalc.getValue()}`); // 15<br><br>// สั่งลบ 3<br>app.executeCommand(new SubtractCommand(myCalc, 3));<br>console.log(`ลบ 3 -&gt; ผลลัพธ์: ${myCalc.getValue()}`); // 12<br><br>// เริ่มทำการ Undo ย้อนกลับทีละสเต็ป!<br>console.log(&quot;--- เริ่มทำ Undo ---&quot;);<br><br>app.undo(); // จะไปเรียก undo() ของ SubtractCommand (บวก 3 กลับเข้าไป)<br>console.log(`Undo ครั้งที่ 1 -&gt; ผลลัพธ์: ${myCalc.getValue()}`); // 15<br><br>app.undo(); // จะไปเรียก undo() ของ AddCommand (ลบ 5 ออก)<br>console.log(`Undo ครั้งที่ 2 -&gt; ผลลัพธ์: ${myCalc.getValue()}`); // 10</pre><h4>สรุป</h4><p>Design Patterns ไม่ใช่กฎตายตัวที่เรา “ต้อง” ใช้กับทุกการเขียนโค้ด แต่เป็นเหมือน <strong>เครื่องมือในกล่อง</strong> ที่เมื่อคุณเจอสถานการณ์หรือปัญหาที่ตรงกับรูปแบบเหล่านี้ เราจะรู้ทันทีว่าควรหยิบเครื่องมือชิ้นไหนออกมาใช้ เพื่อให้โค้ดของเราออกมาดีและดูแลรักษาง่ายที่สุดครับ</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1ced201230d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cloudflare + wordpress กับปัญหา Too many redirects]]></title>
            <link>https://medium.com/odds-team/aws-cloudflare-wordpress-%E0%B8%81%E0%B8%B1%E0%B8%9A%E0%B8%9B%E0%B8%B1%E0%B8%8D%E0%B8%AB%E0%B8%B2-too-many-redirects-a7d36f416461?source=rss-4570570b2ddb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7d36f416461</guid>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[wordpress]]></category>
            <dc:creator><![CDATA[Jirayu Photisan]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 10:25:25 GMT</pubDate>
            <atom:updated>2026-08-02T09:16:33.689Z</atom:updated>
            <content:encoded><![CDATA[<p>หลาย ๆ คนน่าจะคุ้นชื่อ Cloudflare กันอยู่แล้ว นอกจารการการใช้ป้องกันการโจมตีแบบ DDoS แล้วยังช่วยให้การทำให้การทำ HTTPS ของเราง่ายขึ้นมากและที่สำคัญ ฟรีด้วย (ดีตรงนี้แหละ)</p><p>เริ่มจากมาดูที่ไปที่มาของ Design กันก่อน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ziwZmW6QmoKt-kRYobtD_w.png" /><figcaption>การเชื่อต่อระหว่าง cloudflare กับ server</figcaption></figure><p>จะเห็นได้ว่าระหว่าง Browser วิ่งเข้า cloudflare นั้นเป็น HTTPS แล้วหลังจาก cloudflare เข้าสู่ Server เรานั้นเป็น HTTP อาจจะดูไม่ยังไม่ค่อยสบายใจ แต่เนื่องจาก website เรานั้นไม่ได้ต้องการความปลอดภัยมากมากเนื่อหาเน้นแสดง content เลยยังไม่กังวลในส่วนนี้</p><p>มาถึงในส่วนของ Server ของเรา เลือกใช้ Nginx เป็น Gateway คั่น Wordpress</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*bbrwpzk42Sd1mporm6K3FQ.png" /></figure><p>หลังจากนั้นเรามีความต้องการ deploy wordpress ตัวที่ 2 ซึ่งอาจจะมี config ของ nginx ที่ไม่เหมือนกันและอยากเก็บ config nginx ไว้ที่ git เลยเลือกใช้ท่า docker compose</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E2LKAbgTou6ojkasizHs7w.png" /><figcaption>หลังจากเพิ่ม wordpress ตัวที่ 2</figcaption></figure><p>ดูๆ ก็ไม่น่าจะมีอะไรผิดปกติ แต่ ๆๆ จู่ๆ web ก็เข้าไม่ได้ ตอบ 301 มารัวๆ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNVgRFSXcVok8150UGd1jQ.png" /></figure><p>หลังจากที่ไล่เช็คที่ละ layer จาก Nginx ตัวหน้าสุด ไปจนถึงตัว wordpress สุดท้ายก็เจอว่า คนที่ตอบ 301 ก็คือ wordpress นั่นเอง แต่สิ่งที่ไม่เข้าใจก็คือ “ทำไม” นั่นสิ ทำไมนะ การที่เพิ่ม Nginx proxy มาอีกตัวไม่น่าจะทำให้เกิดเหตุการณ์นี้ได้ หลังจากหาสาเหตุมาหลายวัน สุดท้ายคงต้องถึงมือ พระอาจารย์ เจเจ</p><p>หลังจากที่ไล่ดู config nginx กันใหม่จนอิ่มเอมแล้ว พระอาจารย์บอกว่า เราไล่ code wordpress กันเถอะ เผื่อเจออะไร (หลังจากนี้น่าจะต้องพึ่งญาณทิพย์ล้วนๆ ) หลังจากที่ดูไฟล์ของ wordpress แล้ว มีไฟล์ที่เข้าตาก็ไฟล์แรกก็คือ wp-config.php พอไล่ๆ ไปก็เจอผู้ต้องสงสัย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6n_kBiA1_Xz7DS1bvcU1Ow.png" /></figure><p>ใน code บอกว่าถ้าเราอยู่หลัง proxy แล้วใช้ HTTPS ช่วยไปดู แถวๆ นี้หน่อย <a href="https://developer.wordpress.org/advanced-administration/security/https/#Using_a_Reverse_Proxy">https://developer.wordpress.org/advanced-administration/security/https/#Using_a_Reverse_Proxy</a></p><p>หนทางเริ่มสว่าง เมื่อเจอท่อนนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JKICH79PDjSi6rRJqjN0Sg.png" /></figure><p>wordpress บอกว่าถ้าใช้ nginx เรามี config ให้</p><pre>location / {<br>    proxy_pass http://your_host_name:your_port;<br>    proxy_set_header Host $host;<br>    proxy_set_header X-Real-IP $remote_addr;<br>    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>    proxy_set_header X-Forwarded-Host $server_name;<br>    proxy_set_header X-Forwarded-Proto $scheme;<br>    proxy_redirect off;<br>}</pre><p>หลังจาก แก้ config web เราก็กลับมาปกติแล้ว เย้ๆ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ycHfGdDSpG7P5jZpya6tXg.png" /></figure><p>Bonus</p><p>ใน google chrome เราอาจจะเจอ error mixedcontent แล้วรูปจะไม่ขึ้น ให้ลง plugin เพิ่มเติมดังนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vqvwvmGQpAt6RgkRsD7bbw.png" /></figure><p>ส่วนของ config ให้เลือกที่ Support cloudflare</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqegVK0TnEOysqDECzc6oA.png" /></figure><p>ขอให้สนุกครับ</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7d36f416461" width="1" height="1" alt=""><hr><p><a href="https://medium.com/odds-team/aws-cloudflare-wordpress-%E0%B8%81%E0%B8%B1%E0%B8%9A%E0%B8%9B%E0%B8%B1%E0%B8%8D%E0%B8%AB%E0%B8%B2-too-many-redirects-a7d36f416461">Cloudflare + wordpress กับปัญหา Too many redirects</a> was originally published in <a href="https://medium.com/odds-team">odds.team</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter beginner (installation part)]]></title>
            <link>https://medium.com/@gdunghi/flutter-beginner-installation-part-49b6ea661150?source=rss-4570570b2ddb------2</link>
            <guid isPermaLink="false">https://medium.com/p/49b6ea661150</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[installation]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Jirayu Photisan]]></dc:creator>
            <pubDate>Sun, 16 Sep 2018 14:30:35 GMT</pubDate>
            <atom:updated>2018-09-16T14:30:35.605Z</atom:updated>
            <content:encoded><![CDATA[<p>วันนี้ได้มีโอกาสได้ทำความรู้จัก Flutter (mobile cross platform จาก google) เขียนด้วยภาษา Dart มาเริ่มกันเลยดีกว่า</p><p>Download flutter</p><p><a href="https://flutter.io/get-started/install/">Get Started: Install</a></p><pre>cd ~/workspace<br>$ unzip ~/Downloads/flutter_macos_v0.7.3-beta.zip</pre><p>จากนั้น Set path เพื่อให้รู้จักคำสั่ง flutter โดยแก้ไขที่ไฟล์ .bash_profile</p><pre>cd ~<br>vi .bash_profile</pre><p>เพิ่ม</p><pre>PATH= ${flutter_path}/flutter/bin:$PATH</pre><ul><li>** ${flutter_path} คือ path ที่เรา แตก zip flutter_macos_v0.7.3-beta.zip</li></ul><p>Flutter ต้องการ Android emulator โดยเราต้อง install Android studio พร้อมกับ SDK และ emulator</p><p><a href="https://developer.android.com/studio/install">Install Android Studio | Android Developers</a></p><p>จากนั้น ทำการตรวจสอบ libary ที่ flutter ต้องการ</p><pre>flutter doctor</pre><p>ตอนนี้เราสนใจเฉพาะ android ก่อน ถ้าผ่าน ผลลัพธิ์จะประมาณนี้</p><pre>Doctor summary (to see all details, run flutter doctor -v):<br>[✓] Flutter (Channel beta, v0.7.3, on Mac OS X 10.13.6 17G65, locale en-TH)<br>[✓] Android toolchain — develop for Android devices (Android SDK 27.0.3)</pre><p>ตอนนี้เราพร้อมจะ create project กันแล้ว !!! เร่ิมกันเลย</p><pre>flutter create flutter101<br></pre><p>ต่อจากนั้นเราต้อง start android emulator ก่อน โดยเปิด android studio แล้ว start project เปล่าๆ ขึ้นมา จากนั้นไปที่ Tools → AVD Manager จากนั้น create virtual device ผมเลือก Pixel2 (เพราะชอบ) จากนั้น Next จน finish</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_6g7hgFKrXNpk5EUKrNFw.png" /></figure><p>จากนั้น Lunch Android AVD in Emulator</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*LJuwe0JqT6QHYYHOTRAL7w.png" /></figure><p>ตอนนี้เราพร้อมที่จะ run แล้ว</p><pre>cd flutter101</pre><pre>flutter run <br></pre><p>หลังจาก เรา create project default ของ app เราจะเป็นโปรแกรมนับเลข</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*vbHSzXC87EwULSen1FNQ1Q.png" /></figure><p>ขอจบ part 1 ไว้เพียงเท่านี้</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49b6ea661150" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>