Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Write Good Code

0.00/5 (No votes)
22 Nov 2015 2  
Each function should answer how-what-why.

My first tip!

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
{
  VerifyRegistered<T>();
  VerifyInstanceOption<T>();
  IService instance = CreateInstance<T>();
  instance.Initialize(this);

  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 would benefit from "how", "what" or "why" comments, then this is great indicator that you should move those fragment into separate functions where the the function name describes "what" and embodies "how."  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's name answers "what" and the body of the function clearly describes "how", then for each function you created, write an intelligent "why" comment.

Now go forth and code better!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here