Liskov Substitution Principle in Ruby

Liskov Substitution Principle in Ruby

Assume that we already had the code:

1
2
3
4
5
6
7
8
9
10
11
class Animal
  def walk
     do_some_walkin
  end
end

class Cat < Animal
  def run
    run_like_a_cat
  end
end

This principle applies only to inheritance. In order to comply with the Liskov Substitution Principle, Subtypes must be substitutable for their base types.

Well, so they must have the same interface. Since ruby does not have abstract methods, we can do it like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Animal
  def walk
    do_some_walkin
  end

  def run
    raise NotImplementedError
  end
end

class Cat < Animal
  def run
    run_like_a_cat
  end
end

So far so good, That’s it!!! See ya!!! :)