The Art of Cleanliness


I remember when I first looked at this code. There was so much repetition that I thought the previous developer’s Ctrl, C, and V keys would be worn to nubs. Method after method of the same scaffolding code, the same setup and breakdown, with only the core or “meat” of the functionality a mere couple of lines.

Code clutter is the same as work space clutter. It cuts into your ability to efficiently get the job done, be it visually tracing through a hunk of code or finding that “zen” moment when writing a paper. Clutter is a distraction, and the same applies to code. Bottom line is: the less time I spend hunting down the code I need to change, the quicker I can be done and have a beer.

My philosophy is: if you copy and paste it once, you’re doing it wrong*.

*Now, obviously I don’t mean copying and pasting a method name to re-use! No, no! In this context, I mean a method body, or Enum, or set of declarations.

A fellow developer that I worked with (who unfortunately was laid off, among others), and I had spent a lot of time re-factoring much of this code to reduce redundancies. We made great use of C# lambda methods to wrap the meat of our code into an anonymous method inside of the body of our calling method. Here’s an example.

Image title

This is an example of a piece of code that sits in the data layer and will invoke a SQL stored procedure. In this case, it’s to break up two accounts that are linked in our system, but that’s irrelevant. Now, the method by itself isn’t bad, and the setup and breakdown is justified. The problem is, EVERY method has the same set of scaffolding. What we want to do is simplify this to make just the code needed by the method visible, with everything else hidden, behind the scenes. Below is the result of this same method.

Image title

How we got here really isn’t difficult. We merely utilized an anonymous method (via a lambda) to sort of “expose” just what we need.

Below is the code that does the heavy lifting. This isn’t the exact method, as there’s a couple layers of overloads (ExecuteCommand is wrapped by ExecuteProcedure, as well), but it ends up here:

Image title

As you can see, it looks very similar to the original method. However, EVERY method that invokes a SQL stored procedure can now utilize this scaffolding code. Not only does it reduce the sheer amount of code visible to a tired developer, but eliminates errors caused by copy/paste errors and typos. Note that we also removed the nested try/catch, as it wasn’t needed, and removed some unneeded declarations.

Now, this is just one example of how some light housekeeping can bring down the level of headache when writing and debugging code. I find utilizing lambdas to be a very powerful method of removing clutter from your code base.

Other Posts