This is the fifth of five posts talking about the SOLID principles. This principles are a great guide to write good source code. Each post will talk about one of the principles:
- S Single responsability principle
- O Open/Closed principle
- L Liskov substitution principle
- I Interface segregation principle
- D Dependency inversion principle
Dependency inversion principle
High-level modules and classes should not depend on low-level ones. Software elements of high-level like business objects should not depend on file systems, operating systems or user interfaces.
Sample
You have a Person class to store all data of the user and define some methods. In order to make this class not dependant on the database or the user interface
class ConcreteUI
end
class Person
def initialize(name, age)
@name
@age
end
def createA
# some code
end
def show
ui = ConcreteUI.new
ui.show("name #{person.name}")
ui.show("age #{person.age}")
end
end
It’s better to make Person class independent from a ConcreteUI using protocols
class Person
def initialize(name, age)
@name
@age
end
def createA
# some code
end
end
class UI
end
class ConcreteUI < UI
end
class PersonRepresentation
def initialize(ui, person)
@ui = ui
@person = person
end
def show
@ui.show("name #{person.name}")
@ui.show("age #{person.age}")
end
end