Interface Segregation Principle (ISP)

drajatisme

drajatisme

Posted on September 8, 2023

Interface Segregation Principle (ISP)

Robert C. Martin menjelaskan:

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

Dave Cheney menjelaskan:

The Interface Segregation Principle takes that idea further and encourages you to define functions and methods that depend only on the behaviour that they need. If your function only requires a parameter of an interface type with a single method, then it is more likely that this function has only one responsibility.

Berikut contoh kode yang mematuhi ISP:

type ShapeCalculator interface {
    Area() float64
    Volume() float64
}

type Square struct {
    Side float64
}

func (s Square) Area() float64 {
    return math.Pow(s.Side, 2)
}

func (s Square) Volume() float64 {
    return 0
}

type Cube struct {
    Side float64
}

func (c Cube) Area() float64 {
    return 0
}

func (c Cube) Volume() float64 {
    return math.Pow(c.Side, 3)
}
Enter fullscreen mode Exit fullscreen mode

Terlihat bahwa menghitung luas hanya untuk tipe Square atau persegi dan volume hanya untuk tipe Cube atau kubus. Untuk membuat kode tersebut menerapkan ISP, maka interface ShapeCalculator harus dipisah menjadi AreaCalculator dan VolumeCalculator:

type AreaCalculator interface {
    Area() float64
}

type VolumeCalculator interface {
    Volume() float64
}
Enter fullscreen mode Exit fullscreen mode

Referensi

💖 💪 🙅 🚩
drajatisme
drajatisme

Posted on September 8, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related