A Method Should Do One Thing and One Thing Only

As someone who enjoys well-written code like it's nobody's business, I get frustrated when I find methods that do more than one thing because to me, a method that *could* perform several actions is not well-written.

For example, awhile back I came across a method named something like CreateUpdateDeleteItem. The name itself contains three verbs (actions for the grammar impaired), and not only that, but it accepts several parameters, a couple of which are used as flags for conditional logic at different places within the method.

The biggest problem with a method like this is testing. The method itself does not subscribe to the Single Responsibility Principle, and thus contains several nested conditional statements, each of which require their own test permutation to make sure all code paths have been accounted for.

Before I got into unit testing a few years ago, I had a much harder time convincing people of the benefits of splitting a method like CreateUpdateDeleteItem into three separate methods (other than "just because"), but with unit tests I have concrete evidence of why it makes sense to do so. It's amazing what happens when you show someone actual tests because at that point it's no longer theory, it's real. And it's usually only then that the light goes off.

So if you find multi-action methods like CreateUpdateDeleteItem, refactor them appropriately. Your tests will thank you.

Print | posted on Wednesday, May 07, 2008 9:47 PM

Feedback

# re: A Method Should Do One Thing and One Thing Only

Gravatar left by Steven Harman at 5/7/2008 11:42 PM
I've been reading a lot of code (mainly OSS projects) looking for some real code I can use in a talk about mocking that I'm putting together. And you know what I've found - there is a lot of code out there w/a zero on the testability scale!

It really makes me wonder if its even possible to write well factored and well designed code is even possible in a non TDD/BDD culture!* Speaking of which... know of any OSS projects that you could point to as an example of _how to_ write testable code?

* = yeah, I know its possible, but it requires a lot more effort and discipline that going the xDD route does!

# re: A Method Should Do One Thing and One Thing Only

Gravatar left by jennifer at 5/8/2008 8:09 AM
this is a principle in tech writing as well---

# re: A Method Should Do One Thing and One Thing Only

Gravatar left by Kevin Upchurch at 5/9/2008 7:08 AM
Why would the light go off after you show someone units tests? Are you dimming down the developer community :)
Comments have been closed on this topic.