SOLID: Interface Segregation Principle

Programming

SOLID: Interface Segregation Principle

อย่าบังคับให้รับในสิ่งที่ไม่อยากได้

3 เดือนที่ผ่านมา

1 min read

Table of Contents

Clients should not be forced to depend upon interfaces that they do not use.

สรุปง่ายๆ เวลาที่เราสร้าง class จาก protocol เราไม่ได้อยากจะ implement method ทั้งหมด แต่ก็ต้องสร้างเพราะว่า protocal นั้นบังคับไว้

ซึ่งแน่นอน ISP ก็บอกว่าเราไม่ควรจะทำแบบนั้น เราควรที่จะ implement method เท่าที่จะใช้ อันไหนไม่ใช้ก็ไม่ต้องเอามา

❌ Bad

อย่างเช่นในตัวอย่างนี้มี protocol MusicPlayer บางทีผมอาจจะอยากได้แค่ mothod play(), pause() และ stop() แต่ก็จำเป็นต้อง implement method อื่นๆ ด้วย เพราะ protocal นั้นบังคับ

protocol MusicPlayer {
    func play()
    func pause()
    func stop()
    func skip()
    func shuffle()
    func repeat()
    // ... many more methods ...
}
 
class AdvancedMusicPlayer: MusicPlayer {
    func play() {
        // Implementation
    }
    // ... Implementing all other methods ...
}

✅ Good

ทางที่ดีเราควรจะแยก protocal เพื่อแบ่งตามประเภทการใช้งาน อย่างเช่นในตัวอย่าง แบ่งออกมาเป็น 2 อัน อันนึงคือ BasicMusicPlayer และ AdvancedMusicPlayer

protocol BasicMusicPlayer {
    func play()
    func pause()
    func stop()
}
 
protocol AdvancedMusicPlayer: BasicMusicPlayer {
    func skip()
    func shuffle()
    func repeat()
}
 
class SimpleMusicPlayer: BasicMusicPlayer {
    func play() {
        // Implementation
    }
    // ... Implementing other basic methods ...
}
 
class SmartphoneMusicPlayer: AdvancedMusicPlayer {
    func play() {
        // Implementation
    }
    // ... Implementing advanced methods like skip, shuffle, repeat ...
}

ทีนี้ถ้าผมอยากได้แค่ method play(), pause(), stop() ผมใช้แค่ protocal BasicMusicPlayer

Tags:

Swift SOLID