Weel 2, Day 2
Good morning everyone,
In our standups today, we have discussed yesterday’s ups and downs and then received a task to research the SOLID principles, in particular dependency inversion, and write a post. You can ind below the work Mo and I have done.
SOLID
S.O.L.I.D is an acronym for the first five object-oriented design (OOD) principles by Robert C. Martin, popularly knows as Uncle Bob.
When working with software in which dependency management is handled badly, the code can become rigid, fragile and difficult to reuse. Rigid code means it is difficult to modify, either to change existing functionality or add new features. Fragile code is susceptible to the introduction of bugs, particularly those that appear in a module when another area of code is changed. If you follow the SOLID principles, you can produce code that is more flexible and robust, and that has a higher possibility for reuse.
S.O.L.I.D stands for
- S - Single-responsibility principle
 - O - Open-closed principle
 - L - Liskov substitution principle
 - I - Interface segregation principle
 - D - Dependency Inversion principle
 
Dependency Inversion Principle
The dependency inversion principle means that the Abstract (Higher level) class should not dependent on another class. For example, let’s take the Abstract class Board and the lower class Ship which interacts with:
class Board
  def coordinates
    "generates coordinates"
  end
  def place
    Ship.new.place(coordinates)
  end
end
class Ship
  def place(coordinates)
    "places ship in #{coordinates}."
  end
end
This example violates this principle, because the Abstract class (i.e. Board) is dependent on another class (i.e. Ship) within one of its own methods (the method: place).
Let’s fix this now:
class Board
  def coordinates
    "generates coordinates"
  end
  def place(klass = Ship.new)
    klass.new.place(coordinates)
  end
end
class Ship
  def place(coordinates)
    "places ship in #{coordinates}."
  end
end
As you can see here, the Abstract Board class is no longer dependent on the (lower level) Ship class since its place method no longer implicates the Ship class within it but rather incorporates it as an argument. This keeps things flexible as we can pass any other class instances - i.e. Car.new, Plane.new without compromising the Abstract class.
Zhivko & Mo