Design Patterns ที่ช่วยให้จัดการ Legacy Code ได้ง่ายขึ้น

การทำงานกับ Legacy Code บางทีก็เหมือนเดินในทุ่งกับระเบิด—ไม่รู้ว่าเมื่อไหร่โค้ดจะระเบิดใส่เรา 💣 แต่ข่าวดีก็คือ...
Design Patterns (รูปแบบการออกแบบซอฟต์แวร์) คือเครื่องมือทรงพลังที่จะช่วยให้คุณควบคุมและจัดการกับ Legacy Code ได้อย่างมีประสิทธิภาพ


🧩 1. Adapter Pattern — ตัวแปลงอินเทอร์เฟซ

ปัญหา: โค้ดเก่าใช้โครงสร้างที่ไม่ตรงกับสิ่งที่ระบบใหม่ต้องการ
แนวทางแก้: สร้างคลาสตัวกลางที่ “แปลง” อินเทอร์เฟซให้เข้ากันได้

ตัวอย่าง:

# legacy_system.py
class LegacyPaymentProcessor:
    def make_payment(self, amount):
        print(f"[Legacy] ชำระเงินจำนวน ${amount}")
# adapter.py
class PaymentInterface:
    def pay(self, amount):
        raise NotImplementedError

class LegacyAdapter(PaymentInterface):
    def __init__(self, legacy_processor):
        self.legacy_processor = legacy_processor

    def pay(self, amount):
        return self.legacy_processor.make_payment(amount)

การใช้งาน:

adapter = LegacyAdapter(LegacyPaymentProcessor())
adapter.pay(100)

✅ ระบบใหม่สามารถใช้งานผ่าน PaymentInterface ได้เลยโดยไม่แตะต้องโค้ดเก่า


🏗️ 2. Facade Pattern — หน้ากากที่ซ่อนความซับซ้อน

ปัญหา: ระบบเก่าซับซ้อน ใช้งานยาก
แนวทางแก้: สร้างอินเทอร์เฟซเดียวที่เรียกใช้ทุกอย่างแทน

ตัวอย่าง:

class LegacyAuth:
    def check_user(self, username, password):
        return username == "admin" and password == "1234"

class LegacyLogger:
    def log(self, msg):
        print(f"[LOG]: {msg}")
class AuthFacade:
    def __init__(self):
        self.auth = LegacyAuth()
        self.logger = LegacyLogger()

    def login(self, username, password):
        if self.auth.check_user(username, password):
            self.logger.log(f"{username} เข้าระบบสำเร็จ")
            return True
        self.logger.log("ความพยายามเข้าสู่ระบบล้มเหลว")
        return False

✅ ใช้งานง่าย แค่เรียก AuthFacade().login(...) ก็จัดการระบบเบื้องหลังทั้งหมดแล้ว


🧪 3. Decorator Pattern — เติมพลังให้โค้ดเก่า

ปัญหา: อยากเพิ่มฟีเจอร์ใหม่โดยไม่แก้โค้ดเก่า
แนวทางแก้: สร้าง "ตัวห่อ" (Wrapper) เพื่อเพิ่มพฤติกรรม

ตัวอย่าง:

class LegacyReporter:
    def report(self):
        print("สร้างรายงานพื้นฐาน...")

class TimestampedReporter:
    def __init__(self, wrapped):
        self.wrapped = wrapped

    def report(self):
        from datetime import datetime
        print(f"เวลารายงาน: {datetime.now()}")
        self.wrapped.report()

✅ ต่อยอดได้โดยไม่แตะต้องระบบเก่าเลย


🧰 4. Strategy Pattern — เปลี่ยนพฤติกรรมได้อย่างยืดหยุ่น

ปัญหา: อยากเปลี่ยน “วิธีทำงาน” ของโค้ดโดยไม่แก้โค้ดเดิม
แนวทางแก้: แยกพฤติกรรมออกเป็นโมดูล แล้ว inject เข้าไป

ตัวอย่าง:

class LegacySorter:
    def sort(self, data):
        return sorted(data)

class ReverseSortStrategy:
    def sort(self, data):
        return sorted(data, reverse=True)

class SorterContext:
    def __init__(self, strategy):
        self.strategy = strategy

    def sort(self, data):
        return self.strategy.sort(data)

✅ ปรับเปลี่ยนพฤติกรรมการทำงานโดยแค่เปลี่ยน strategy


🚦 5. Proxy Pattern — ควบคุมการเข้าถึงระบบเก่า

ปัญหา: อยากเพิ่ม log หรือควบคุมสิทธิ์โดยไม่ยุ่งกับโค้ดเดิม
แนวทางแก้: ใช้คลาสตัวแทนในการควบคุมการเข้าถึง

ตัวอย่าง:

class LegacyDatabase:
    def query(self, sql):
        print(f"กำลังเรียกใช้ SQL: {sql}")
        return f"ผลลัพธ์สำหรับ: {sql}"

class LoggingProxy:
    def __init__(self, db):
        self.db = db

    def query(self, sql):
        print(f"[LOG] ก่อนรัน: {sql}")
        return self.db.query(sql)

✅ ปลอดภัย และง่ายต่อการ debug


🔚 สรุปส่งท้าย

Design Patterns คือทางรอดในการทำงานกับโค้ดเก่าๆ
ลองเริ่มต้นจาก 5 รูปแบบนี้ แล้วคุณจะควบคุม Legacy Code ได้ดีกว่าที่เคย

หลักการสำคัญ:

  • ห่อ แยก และแทน ไม่ต้องรีบแก้โค้ดเก่า
  • ค่อยๆ refactor ไปทีละจุด
  • เขียน test รองรับทุกการเปลี่ยนแปลง

หากคุณกำลังจัดการโค้ดเก่าๆ ในโปรเจกต์ของคุณเอง แล้วอยากให้ช่วยดูหรือช่วย refactor ก็บอกได้เลย! 😎


Related Posts

Articles

Our Products


Related Posts

Articles

Our Products


Get in Touch with us

Speak to Us or Whatsapp(+66) 83001 0222

Chat with Us on LINEiiitum1984

Our HeadquartersChanthaburi, Thailand