Wednesday, July 10, 2013

SOLID: Single Responsibility Principle (SRP)


Even after five years of programming, I am still struggling with this principle. I don't know how to determine if a method is part of the class responsibility. In the Agile Software Development Principles, Patterns, and Practices book, Uncle Bob has this class structure:

At first glance, the design feels ok to me. The Rectangle class has an area and it knows how to draw itself. In my Tic Tac Toe, I have a similar logic for the players. I let the players give me a move by injecting a strategy in the player class. For a computer player, that means using minimax strategy. For a human player, a console "strategy" which really means display a message to the user to get the user input. This felt like a good design because the game doesn't have to worry about getting input. It doesn't even know what type of players it has.

However, after I watched the Clean Coder video, I understood what Uncle Bob means when he said it should change for one, and only one reason. Instead of thinking about responsibility, think about who uses the methods in the class. For example, look at this this class:
public class Employee {
  public Money calculatePay()
  public String reportHours()
  public void update()
  public void add()
}

Who will use these methods?

  • Someone who needs to know how much to pay the employee (aka payroll system)
  • Someone who needs to add/update the employee information

When you think about it that way, you can clearly see that these methods should be in two classes. And it makes sense because if you change the database schema, update() and add() need to know about it. But that doesn't have anything to do with reported hours or pay calculation.

Looking back at the graph, I can see why that is a violation of the single responsibility principle. The draw method uses the GUI and the computational class uses area. The application also uses the GUI. So when the GUI change, Rectangle has to change even though the area code didn't.

As for my Tic Tac Toe program, maybe it's ok because the class that gets the move is the strategy class, and the strategy only have one reason to change, which is how it gets the player's move.

0 comments:

Post a Comment