Keep Methods Focused to Support Re-use
You may have seen a method that has two or three required parameters and half-a-dozen optional Boolean parameters. On investigation, you discover that the optional parameters each turn off some processing that the method would normally perform (typically, these parameters have names like NoUpdate, SkipAudit). This is evidence of a failure in designing the method.
What's happened here is that a developer originally wrote the method to do 13 things -- but then all the other developers who used that method asked for the ability to turn off some of those 13 things. So one by one, those Boolean parameters got added. And, with each new option, the code in the method became more complicated and harder to debug (or test).
It may seem like a good idea to create one method that takes care of 13 things. For instance, a method for purchasing a product might have all the code to check that the product is in stock, to decrement the quantity of the product on hand, to create a new line on an order (and create the order if it doesn't already exist), to write a log record to the audit trail, and so on. But what if a developer wants to call your method and only wants to do 12 of those 13 things? For instance, when the customer is buying a service (rather than a physical product), there's no stock to check or inventory to decrement. A developer supporting buying services will want to turn that functionality off in the purchase product method.
The "single responsibility principle" is usually discussed in terms of objects, but it's actually more obvious in methods. A method that does exactly one thing (that has a single responsibility) is probably easier to write and understand (and certainly easier to test) than a method that does many things. More importantly, that method is more useful: Developers can mix and match whatever "single responsibility" methods they need to get the result they want. So, instead of building one big method, you're better off building 13 more focused methods: A method to check stock, a method to decrement inventory, a method to create a line on the order, and so on.
But, you may say, the typical activity is to do those 13 things. If that's the case, then there's nothing stopping you from creating a new method that calls the 13 individual methods in the right order to do the "typical" thing. Developers doing the "typical" thing can call your new method (which is, by the way, an example of the Façade pattern). But developers still have the ability to mix and match the other 13 methods when they want to do something "un-typical."
Posted by Peter Vogel on 02/19/2013 at 4:25 AM