Refactoring

Last night, I went to a presentation on refactoring by Jonathan Cogley.  My notes are below:

refactor – improve the design of existing code incrementally

Code must:

  • do the job
  • be maintainable/extensible
  • communicate its intent

Code that doesn’t accomplish all of the above is broken.

Refactorings

  • rename
  • extract method
  • inline method
  • introduce explaining variable
  • move method
  • inline temp

technical debt – anything that needs to be done to the code that gets put off until a later date

I found a much better definition for technical debt.  It makes a nice argument in favor of refactoring (though not as good as it would be with some way to quantify and measure it).

code smell – indication that something could be wrong with the code

Code Smells

  • duplicated code
  •  long methods
  • large classes
  • Too many private/protected methods
  • Empty catch clause (FxCop flags these by default)
  • Too many static methods
  • Variables with large scope
  • Poorly-named variables
  • Comments
  • Switch statements
  • Unnecessary complexity

Even though comments in code to tend to get out of date, I’m not sure I’d call them a code smell.  Wikipedia has another definition of code smell, along with a link to a taxonomy of code smells.

When to refactor:

  • before a change
  • after all current tests are green

Sometimes, refactoring is necessary to understand code.

reduce scope – bring variable closer to where it’s used

Be sure your unit tests don’t re implement what the tested code is doing.

Eliminate double assignments (a = b = 0) for clarity.

Each method should have only one operation/concept.

If you must use code comments, they should explain the “why”.  The code should be clear enough to explain the “what”.

Favor virtual instance methods where possible in your code.

Avoid using the debugger.  Write unit tests instead.

Performance improvements tend to make code harder to understand.  Don’t use refactoring to address application performance.

Recommended reading:

Refactoring to Patterns

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.