O of SOLID (2/5)

Posted by Daniel Vela on February 19, 2018

This is the second 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:

Open/Closed principle

Any sowftware entity, like the source code or classes, must be open to expand, and closed to change. You must include new funtionality to a class without changing the previous functions.

Ways to expand functionality

There is only one ways to expand the methods of one class: using inheritance

There is two types of inheritance to expand code:

  1. Use a specialized class to include new functionality or improve the previous one.
  2. The other way is to expond some beheviours of the code to abstract classes (like Swift protocols), to be implemented in the future

Sample

This shape class has two responsabilities, to be a circle and sometimes a square

class Shape
  def makeCircle(radious)
    @type = :circle
    @radious = radious
  end
  def makeSquare(side)
    @type = :square
    @side = side
  end
  def area
    if @type == :circle
      2 * M_PI * @radious
    elsif @type == :square
      side * side
    end
  end
end

It’s better to define two classes, one for each responsability

class Shape
  def area
  end
end

class Circle < Shape
  def make(radious)
    @radious = radious
  end
  def area
    2 * M_PI * @radious
  end
end

class Square < Shape
  def make(side)
    @side = side
  end
  def area
    side * side
  end
end

It’s easier to mantain and to expand. This way it can be possible to expand the code with new shapes without changing the rest of the classes.