Sunday, November 12, 2017

OOP explained -DESIGN -

OOP design has SOLID principle.

- Single Responsibility Principle (SRP)
- Open Closed Principle
- Liskov's Substitution Principle
- Interface Segregation Principle
- Dependency Inversion Principle

Single Responsibility Principle (SRP)

SRP is so simple. Each class must have only one responsibility for it. Any class should not have more than one responsibility. (For example, Apple class should not have any  methods handling Banana)

Open Closed Principle

It means Open for extension and Closed for modification so that you can easily add new main features to it. This is vital aspect since we need to keep high maintainability of our code base.

Liskov's Substitution Principle

Each class of the same level (inheriting from the same abstract class) should be interchangeable.
In Ruby, for instance, something like:

1.to_s
/^[\/{3}\-]+$/.to_s
"abc".to_s

These above belong to totally different types, but even though they are of different classes but shares the same method to_s which enables it to convert to String since their super class Object has it.

Interface Segregation Principle

Each interface should be segregated and should not included the method which is not required to that particular interface.

Dependency Inversion Principle

Abstract class should be in the middle between interfaces, and details relies on abstract but not vice versa. Like:


class Base::Provider
  def slice
  end
end

class Apple::Provider < Base::Provider
  def slice
  end
end

class Banana::Provider < Base::Provider
  def slice
  end
  def burn
  end
end

class Controller < ActiveRecord
  def create
    backend.provider.slice     
  end
end


Something like this. In OOP we should not dispatch directly to each class implementation or, to say, DSL but we need abstract class in the middle and let it dispatch to the detailed polymorphic classes.



http://www.oodesign.com/dependency-inversion-principle.html

No comments:

Post a Comment