Interface Segregation Principle in Ruby

Interface Segregation Principle

Simply Interface Segregation Principle states that: When a client depends upon a class that contains interfaces that the client does not use, but that other clients do use, then that client will be affected by the changes that those other clients force upon the class.

If you have a class that has two clients (objects using it):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Car
  def open
  end

  def start_engine
  end

  def change_engine
  end
end

class Driver
  def drive
    @car.open
    @car.start_engine
  end
end

class Mechanic
  def do_stuff
    @car.change_engine
  end
end

As you can see, our Car class has an interface that’s used partially by both the Driver and the Mechanic. We can improve our interface like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Car
  def open
  end

  def start_engine
  end
end

class CarInternals
  def change_engine
  end
end

class Driver
  def drive
    @car.open
    @car.start_engine
  end
end

class Mechanic
  def do_stuff
    @car_internals.change_engine
  end
end

So far so good, splitting the interface into two, we can comply to the Interface Segregation Principle. That’s it!!! See ya!!! :)