Introduction 


Anybody can write code. With a few months of programming experience, you can write ‘working applications’. Making it work is easy, but doing it the right way requires more work, than just making it work.
Believe it, majority of the programmers write ‘working code’, but not ‘good code’. Writing ‘good code’ is an art and you must learn and practice it.

Everyone may have different definitions for the term ‘good code’. In my definition, the following are the characteristics of good code.

  • Reliable
  • Maintainable
  • Efficient

Most of the developers are inclined towards writing code for higher performance, compromising reliability and maintainability. But considering the long term ROI (Return On Investment), efficiency and performance comes below reliability and maintainability. If your code is not reliable and maintainable, you (and your company) will be spending lot of time to identify issues, trying to understand code etc. throughout the life of your application.

There are several standards exists in the programming industry. None of them are wrong or bad and you may follow any of them. What is more important is, selecting one standard approach and ensuring that everyone is following it.

 Naming Conventions and Standards


Pascal casing: First character of all words are Upper Case and other characters are lower case.   Example: BackColor

Camel Casing: First character of all words, except the first word are Upper Case and other characters are lower case.   Example: backColor.

  1. Use Pascal casing for Class names
  • public class HelloWorld
  • {
  •      …
  • }
  1. Use Pascal casing for Method names
  • void SayHello (string name)
  • {
  •      …
  • }
  1. Use Camel casing for variables and method parameters
  • int totalCount = 0;
  • void SayHello (string name)
  • {
  •      string fullMessage = “Hello ” + name;
  •      …
  • }
  1. Use the prefix “I” with Pascal Casing for interfaces ( Example: IEntity )
  2. Use Pascal casing for Properties (Example: string FirstName)
  3. Use Meaningful, descriptive words to name variables. Do not use abbreviations.

Good:

  • string address
  • int salary

Not Good:

  • string nam
  • string addr
  • int sal

Do not use single character variable names like i, n, s Use names like index, temp. one exception in this case would be variables used for iterations in loops:

  • for ( int i = 0; i < count; i++ )
  • {
  •      …
  • }

If the variable is used only as a counter for iteration and is not used anywhere else in the loop, many people still like to use a single char variable (i) instead of inventing a different suitable name.

8. Do not use underscores (_) for local variable names.

9. Do not use variable names that resemble keywords.

Ex: Int class = 15;

10. Prefix boolean variables, properties and methods with “is” or similar prefixes.

Ex: private bool isFinished

  1. File name should match with class name.
  2. For example, for the class HelloWorld, the file name should be HelloWorld.cs
  3. Use Pascal Case for file names.

Indentation and Spacing


  1. Use TAB for indentation. Do not use SPACES. Define the Tab size as 4.
  2. Comments should be in the same level as the code (use the same level of indentation).

Good:

  • // Format a message and display
  • string fullMessage = “Hello ” + name;
  • DateTime currentTime = DateTime.Now;
  • string message = fullMessage + “, the time is : ” + currentTime.ToShortTimeString();
  • MessageBox.Show ( message );

Not Good:

// Format a message and display

 

  • string fullMessage = “Hello ” + name;
  • DateTime currentTime = DateTime.Now;
  • string message = fullMessage + “, the time is : ” + currentTime.ToShortTimeString();
  • MessageBox.Show ( message );

3. Curly braces ( {} ) should be in the same level as the code outside the braces.1

4. There should be one and only one single blank line between each method inside the class.

5. The curly braces should be on a separate line and not in the same line as if, for etc.

Good:

  •      if  ( … )
  •      {
  •                 // Do something
  •       }

Not Good:

  •               if ( … ) {
  •                 // Do something
  •            }

6. Use a single space before and after each operator and brackets.

Good:

  •            if  (showResult == true)
  •            {
  •                 for  (int i = 0; i < 10; i++)
  •                 {
  •                      //
  •                 }
  •            }

Not Good:

  •            if(showResult==true)
  •            {
  •                 for(int       i= 0;i<10;i++)
  •                 {
  •                      //
  •                 }
  •            }

7. Use #region to group related pieces of code together. If you use proper grouping using #region, the page should like this when all definitions are collapsed.
2

 

 

 

 

 

 

 

 

8. Keep private member variables, properties and methods in the top of the file and public members in the bottom.

Good Programming practices


1. Avoid writing very long methods. A method should typically have 1~25 lines of code. If a method has more than 25 lines of code, you must consider re factoring into separate methods.

2. Method name should tell what it does. Do not use miss-leading names. If the method name is obvious, there is no need of documentation explaining what the method does.

Good:

  • void SavePhoneNumber ( string phoneNumber )
  • {
  •        // Save the phone number.
  • }

Not Good:

// This method will save the phone number.

  • void SaveDetails ( string phoneNumber )
  • {
  •        // Save the phone number.
  • }

3. A method should do only ‘one job’. Do not combine more than one job in a single method, even if those jobs are very small.

Good:

  •        // Save the address.
  •      SaveAddress (  address );
  • // Send an email to the supervisor to inform that the address is updated.
  •      SendEmail ( address, email );
  •      void SaveAddress ( string address )
  •      {
  •            // Save the address.
  •            // …
  •      }
  •      void SendEmail ( string address, string email )
  •      {
  • // Send an email to inform the supervisor that the address is changed.
  •            // …
  •      }

Not Good:

  •      // Save address and send an email to the supervisor to inform that
  • // the address is updated.
  •      SaveAddress ( address, email );
  •      void SaveAddress ( string address, string email )
  •      {
  •            // Job 1.
  •            // Save the address.
  •            // …
  •            // Job 2.
  •      // Send an email to inform the supervisor that the address is     changed.
  •            // …
  •       }

4. Always watch for unexpected values. For example, if you are using a parameter with 2 possible values, never assume that if one is not matching then the only possibility is the other value.

Good:

  • If ( memberType == eMemberTypes.Registered )
  • {
  • // Registered user… do something…
  • }
  • else if ( memberType == eMemberTypes.Guest )
  • {
  • // Guest user… do something…
  • }
  • else
  • {
  •      // Un expected user type. Throw an exception
  •      throw new Exception (“Un expected value “ +   memberType.ToString() + “’.”)
  •  
  •      // If we introduce a new user type in future, we can easily find
  • // the problem here.
  • }

Not Good:

  • If ( memberType == eMemberTypes.Registered )
  • {
  •      // Registered user… do something…
  • }
  • else
  • {
  •      // Guest user… do something…
  • // If we introduce another user type in future, this code will
  • // fail and will not be noticed.
  • }

5. Do not hardcode strings. Use resource files.

6. Convert strings to lowercase or upper case before comparing. This will ensure the string will match even if the string being compared has a different case.

  • if ( name.ToLower() == “john” )
  • {
  •          //…
  • }

7. Use String.Empty instead of “ ”

Good:

  • If ( name == String.Empty )
  • {
  • // do something
  • }

Not Good:

  • If ( name == “” )
  • {
  • // do something
  • }
Advertisements