How to Write Good Code

This is not a long tome on software architecture.  This is simply about how do to write good code.

Code consists of functions, and this is what a function should look like (using C# style as an example):

// A comment describing why the function exists
void WhatTheFunctionDoes()
  ... how the function does what it says it does.

That’s it! If you follow the “why-what-how” approach, the quality of your code will start to improve!

Here’s a real life example:

/// <summary>
/// The user can get an instance of a service implementing 
/// the specified interface, but only if the service is 
/// registered as supporting instance creation.
/// </summary>
public virtual T GetInstance<T>()
  where T : IService
  IService instance = CreateInstance<T>();

  return (T)instance;
  1. The “why” is clear — we’re supporting a need the programmer will have for creating service instances.
  2. The “what” is clear — the function returns an instance of the specified generic type T.
  3. The “how” is clear — there are four function calls that describe how this function works.

Here’s a simple guideline for figuring out when to break a function apart into smaller functions:  If your function has “how” fragments that ought to have “how”, “what” or “why” comments, then this is great indicator that you should move those fragment into separate functions so that the function name describes “what” and then write a “why” comment for the function.

In other words, when you could write a comment in the body of the code that answers one of those questions, you need to move that code into a function that answers the “what”.  Recurse that process until the function clearly describes “how”, then for each function you created, write an intelligent “why” comment.

Now go forth and code better!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s