Beautiful Code

Indy Code Camp Notes, Part 3

This is part of a four part series of notes I took at Indy Code Camp on May 16, 2009. This year’s Code Camp consisted of five tracks each with five sessions. Track topics were SharePoint, SilverLight and WPF, Data Access, MIX highlights, and best practices. These notes are from the sessions I attended.

These notes are in no way intended to replace attending one of these talks if you have the chance.

Being More Than a Code Monkey: Practicing Beautiful Code

Presented By: Michael Wood – Strategic Data Systems

In this session Michael described some common traits of “ugly” code and presented some guidelines as to what makes code beautiful. Clean Code by Bob Martin is recommended reading for more information on this topic.

Beautiful Code is NOT

  • Hard to follow
  • Hard to extend
  • Something you have to slog through
  • Done with brute force (If it’s really hard to do you’re probably doing it wrong)
  • Code that people run from

Why Should I Care?

  • Working with ugly code can negatively impact project timelines. If code is difficult to understand it will take subsequent developers longer to get to a position to maintain that code. It can also potentially have cross-project impact if previous developers need to be brought in to help explain the code.
  • Code that is difficult to extend will likely require additional refactoring which can possibly seep into additional areas.
  • Like broken windows bad code tends to beget bad code. High quality standards need to be maintained consistently across the application in order to be effective.

Traits of Beautiful Code

  • Self documenting – types and their members should be named according to their purpose. Comments are nice but need to be maintained to be effective as code is changed. By writing self-documenting code the need for comments is significantly reduced if not eliminated.
  • Avoids using magic numbers – anything that could be a magic number should be defined as constant or enum member. Similarly, consider using an abstract class with constant strings to simulate an enum to avoid having hard-coded strings inline.
  • Exceptions carry additional information – the Exception class has a Message property and an InnerException property…USE THEM!

Code Monkey Song by Jonathan Coulton

Michael mentioned this song and video in his presentation so I thought I’d include it. Enjoy!