« back

The Single Responsibility Principle

17 Jul 2012


Yesterday, while working on my second go at Tic Tac Toe, I was wrestling with the Single Responsibility Principle. I realized even if I win, my code would lose.

It started like this... While working on creating a method I thought: "I am doing this one thing, and with three more lines, I can do another thing I need. Genius!" I spent a lot of time trying to crowbar these three lines of code in. I wasn't using my nose. There was a horrible design smell. Okay, I did smell it at first, but thought it was mild, and the payoff would be worth the slightly unpleasant aroma. Maybe I was misunderstanding SRP anyway. I just kept on working. I was going to make this work. I felt like this drawing by hyperbole and a half:

Going crazy at the computer.

Finally, after trying for so long to crowbar those lines in, my arms were tired. I gave up. Then something amazing happened. I was able to finish my method and create a separate one for the lines I was trying to crowbar in. It took about 10 minutes with tests. Wow. Talk about a waste of time trying to do it the other way.

In the book Agile Software Development by Robert C. Martin, he asks why is it important to separate two responsibilities? The answer is that each responsibility is an axis of change. If there is more than one responsibility, the responsibilities become coupled. Changes to one responsibility may impair or inhibit the the ability of the other. They sure do. Thanks Uncle Bob!

comments powered by Disqus