IMG_0048 Matthew Groves speaks about refactoring
At the Code Camp 2013 (primarily a .NET-based conference) in Austin, Matthew Groves gave a talk "A Class That Knew Too Much", about refactoring classes and methods. It was a demonstration on how to refactor a class full of needlessly complicated, spaghetti code. Matthew's method was to give the class single responsibility: that is to say, the class would be doing one, and only one "thing" (loosely speaking).
What does single responsibility give us?
[*] Testability: if a class knows too much, it's harder to test.
[*] Decoupling: if classes are tightly coupled, it can lead to lots of bugs.
Other indications that your classes and methods need to be refactored:
[*] Length: if a method is 200 lines of code, it's doing too much and probably needs to be broken up. Maybe the class itself also needs to be split up into multiple classes.
[*] "Sawtooth" code, or lots of indentations going in and out, indicates there's too much logic in this method. This is related to the concept of cyclomatic complexity.
[*] Ask yourself: would this class have to change if I change
-- the database (e.g. SQL server to RavenDB)?
-- Front-end framework (e.g. ASP.net to Xamarin?)
-- Business rules, such as "you can do X" and "you can't do Y"? If you add another rule, would this class have to change? if so, then it knows too much and needs to be refactored.