DaedTech

Stories about Software

By

ChessTDD 52: The Simple Beauty of Refactoring

In this episode, I decided to be content with the simple beauty of a refactoring.  I’m on the road and quite busy, including some presentations and a lot of driving around to various client sites, so it’s already a tiring week.  Add to that the fact that my car stereo is (was) apparently a hot commodity on the black market, triggering a thief to target my car in the Marriott parking lot while leaving every other car alone, and it’s been a pretty draining week.  So to sit down and code was nice.  But to sit down and clean up/delete code was sublime.

It’s always a win when you can do some cleaning, and so I decided to cap an episode early with nothing but that activity.

What I accomplish in this clip:

  • Refactored GetCastlingMovesFor to be cleaner and more succinct.
  • Laid a solid foundation for implementing castling for black pieces.

Here are some lessons to take away:

  • Trust me — you’re never going to look back later and think, “if only I hadn’t spend those 15 minutes cleaning up this method!”  Take the time.  Clean the method.  You are definitely not going to regret doing so.
  • Avoid “magic” values whenever possible.  Ask yourself if someone reading through your code would say “what on Earth does 7 mean here?”  Take literals and given them meaningful names as constants to be clear on their significance.
  • Code is a lot easier to reason about when it is declarative, rather than imperative.  Whenever possible, write code that expresses “what” and not the details of “how.”
  • It’s okay to give something a temporary nonsense name if you’re in the midst of refactoring and think you might not be done conceiving of what it’s supposed to do.  Just make sure you come back and give it a good name.  Don’t forget!