The Startup
Published in

The Startup

SOLID Principles for beginners

class Dog
def initialize(name = "doggo")
@name = name
end
def walk
puts "I walk"
end
def bark
puts "woof woof"
end

def eat
puts "I eat chimken"
end

def tail(attribute = "pretty")
puts "I have a #{attribute} tail"
end
end
Now, if we want to add another method bite(), it would be super easy to add because our class Dog has just one responsibility that is to behave like a Dog. If we want to add a method fly we need to create another class, because fly is the behavior of a bird.class Bird
def initialize(name = "birdie")
@name = name
end
def fly
puts "I fly"
end
end
class GoldenRetriver < Dog
def bark
"I don't bork unnecessarily"
end

def characteristics
"I am large in size and intelligent and playful"
end

def retrieve(things = "toys")
"I retrieve #{things}"
end
end
class Corgi < Dog
def bark
"I bork pretty lot"
end

def characteristics
"I am small and Cheerful and lively"
end

def herd(thing = "sheep")
"I herd #{thing}"
end
end
Here, both classes are derived from Dog and would behave as a Dog albeit with additional behaviors. Hence the Dog class is closed for modification(We didn't change any methods of the Dog class), and is open for modification(We extended Dog class via inheritance).
class Dog 
def tail(attribute = "pretty")
puts "I have a #{attribute} tail"
end
end
class Corgi < Dog
def tail
raise "I don't have a tail"
end
end
Note: You should be able to use subtypes of class interchangeably, with the instance of parent class, this will allow you to easily swap out different implementations without affecting existing code.
Also, if you have to check instance_of? or something similar before calling a method, it's an indication that you are violating the Liskov substitution.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Anjali Jaiswal

Anjali Jaiswal

23 Followers

Programmer, avid Reader, artist, exploring different trades, fun-loving, adventurous and most of the time a hell-yes person!