S of SOLID (1/5)

Posted by Daniel Vela on February 12, 2018

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

Single responsability principle

One class must have only one responsability. Meaning with responsability any type of task, duty or obligation. The reasons for doing this is to make classes more robust, because if it has only one thing to do, the probability to change this class is lower than if it has multiple responsabilities. If multiple duties are solved with one class, the danger of introducing a bug to a duty when changing another is high.

This principle also helps a lot in order to make testable code, because is easier to test small classes with a few functionalities than hudge classes with tons of functions.

Sample

This User class has too many responsabilities:

class User
  attr :name
  attr :login
  attr :website
  attr :phone
  def initialize(name, login, website, phone)
    @name = name
    @login = login
    @website = website
    @phone = phone
  end
  
  def printUser(printContext)
   # print code
  end
  
  def showUser(screen)
  	# UI Code
  end
  
  def saveUser(fileSystem)
   # file save
  end
end

Programming this way User class has too many dependencies. It depends on the file system, on the print system, and the UI. It’s better to distribute this behiviour through different classes.

class User
  attr :name
  attr :login
  attr :website
  attr :phone
  def initialize(name, login, website, phone)
    @name = name
	@login = login
	@website = website
	@phone = phone
  end
  
class UserPrinter1
  def print(user)
   # print code
  end
end

class UserUI
  def show(user)
  	# UI Code
  end
end

class UserFS
  def save(user)
   # file save
  end
end

This way the new classes are the ones how are dependant on the rest of the system and no the User class.