Sunday, September 6, 2009

Code structure

The standardization of the structure of code is important to allow developers locate objects quickly, trace bugs more effectively and not the least, make the code readable and explanatory. Let us talk about the structure of code today.

I checked multiple sources from Microsoft and also scanned through the code gallery at MSDN to study how people organized their code. I did not find uniformity of order in MSDN samples and other code from the very developers from Microsoft. Some code in gallery even declare member variables at the end of the class while some code use underscore for member variables, which we have strictly avoided. At some point, I thought, we have no rigid reference to stick to, but we will create our standards as close as possible. In fact, I had already speculated that as long as the order of code was followed throughout the application, it hardly mattered which order was put into practice. But I was curiously looking for a scientific order that had explanation. For example, to have events and public methods above private methods makes sense because it helps quicker maintenance, most of the times. There is no scientific backup to support this, but if you work on maintenance of a source for a while, you should feel the same.

First and foremost, "one file, one class" policy is a must. There should not be more than one class in one file. Multiple classes not only tend to make the file size big but also complicate tracing and maintenance. Hence, there should always be one class in a file and the file name according to the class. It is suggested than even if there are objects like enumerators of a namespace level scope, use a separate class for them.

In a source file (C#), the following order should be followed for its contents:

// Copyright information
// File details
// Change log (version history)

Using statements (imports) 

          #region Enumerators (of class level scope) 

          #region Static Methods 

          #region Constants 

          #region Member Variables 

          #region Properties 

          #region Constructors and Destructors 

          #region Events 

          #region Public Methods 

          #region Protected Methods 

          #region Private Methods

Whenever there is question about ordering based on access specifiers, the ordering should always be done in order of: public, protected and private. Hence, if required to classify events based on access specifiers, public events should come first followed by protected and then private ones.

I am already drowsing now, its past midnight. I will limit today’s discussion on code structure to the order of code. Tomorrow, we will discuss sizing code and more. Goodnight!