General C# Coding Standards

Purpose
The objective of this Wiki is to describe rules, recommendations, and practices for developing applications using MS technologies.
These guidelines enforce consistency of style and formatting and help avoiding common mistakes and maintainability issues.
Importance of Coding Standards
“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”
-Martin Fowler
In the project development process, work is result of team effort, several task are distributed among team members. Often you may face situations where you transfer your work to some other person or you may need to involve in projects/tasks that were initially developed by some other person; in some other situation even you could return to a project you written long time ago and you forget anything about it.
Majority of the people write ‘working code’, but not ‘good code’. Writing ‘good code’ is an art and you must learn and practice it.
Imagine if everyone has their own style, own coding standards and conventions then the situation become very complicated and may lead to re-design, re-coding, re- work which increase the cost of the project. Neither any company nor you will like to face such complex situation. 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.
The primary goal you have to achieve while writing code is that your code should exist long time, easy to understand and maintain by others. Most of the developers having a preference towards writing code for higher performance, compromising maintainability. It’s a reality that hardly any software is maintained for its whole life by the original author. Coding standard improve the readability and maintainability of the code, allowing other to understand new code more quickly and thoroughly and even understand their own code more clearly.
Here the term coding standard comes in focus. To develop reliable, maintainable applications and reduce development cost as well as time, you must follow coding standards.
In short advantages of coding standard are:
• Reduce complexity.
• Improve the readability of the code.
• Easy to understand and maintain by others.
• Separate documents appear more appropriate.
• Maintainable applications.
Naming Conventions and Style
“The source code is often the only accurate description of the software. On many projects, the only documentation available to programmers is the code itself. Requirements specifications and design documents can go out of date, but the source code is always up to date. Consequently, it's imperative that the code be of the highest possible quality.”
– Code Complete, Steve McConnell
1. Casing, Prefix, Suffix, and Naming
“It's OK to figure out murder mysteries, but you shouldn't need to figure out code. You should be able to read it.”
– Steve McConnell

1.         Use Pascal casing for types (classes and structures), Interface, Properties, Methods, and Enumerators:


2.         Use camel casing for variables, and method arguments:


3.         Prefix interface with I:

4.         Prefix private member variables with “_” and use camel casing for the rest of name:
5.         Prefix controls with control type hungarian notation “btn” and use Pascal casing for the rest of name:

6.         Suffix attribute classes with “Attribute”:


     
7.         Suffix custom exception classes with “Exception”


8.         Name methods using verb or verb-object pair, and methods with return type should have a name describing the value return:


9.         Use descriptive names:
·            Avoid Hungarian Notations  for public or protected members (don’t prefix or suffix member type in name).
·            Don’t abbreviate words or shorten them unless name is excessive (ex. don’t use “num” instead of “number”).
·            Avoid single character or very short words, even for temp or index fields use index or temp instead.

10.     Use C# predefined types rather than aliases (ex. don’t use “Int32” instead of “int”).
11.     Namespace should be meaningful and use the pattern:

12.      Prefer using instead of typing fully qualified name.

13.     Group all framework namespaces together then custom and other namespaces:
          

14.      Indent comments at the same level of code you are commenting.

15.      When implementing method that could return null prefix it with “Try”. Ex “TryGetItem()

16.      Check spelling of both code and comments.

17.      Declare local variables as close as possible to the code using it.



18.      Use the following regions for each type (when needed):


19.      When using partial classes use partial keyword in both classes, and type the part’s file name as a comment.



20.     Always place a new curly brace “{” in a new line.
21.     Suffix web service reference with “Namespace” keyword;
22.      Don’t use class name in a property (ex.Use MyObj.Name  instead of MyObj.ObjName).
23.      Prefix Boolean members with “Can, Is, or Has”.

2. Commenting
“Good code is its own best documentation. As you're about to add a comment, ask yourself, 'How can I improve the code so that this comment isn't needed?' Improve the code and then document it to make it even clearer.”
– Code Complete, Steve McConnell
1.         Use // or /// but not /* */.
2.         Inline comment algorithms, notes, or business meaning, don’t over describe code, just make it clear.
3.         Use XML commenting for types, methods, and properties:


4.         Avoid comments that explain the obvious, make code clear so you don’t need technical comments (just business oriented comment for each bulk of code).
5.         Never comment out code without mentioning the reason, else remove the code.

General Coding Practices
“The problem with quick and dirty...is that dirty remains long after quick has been forgotten.”
– Software Project Survival Guide, Steve McConnell
1.          Be explicit.
2.          Don’t declare more than one class in a file.
3.          Don’t create more than one namespace in a file.
4.          Avoid files with more than 500 lines (Except generated code).
5.          Avoid methods with more than 200 lines (preferable much less), use helper methods whenever needed.
6.          Use String.ToLower() when comparing.
7.          Avoid methods with more than 5 arguments (use structure of DTO instead).
8.          A line should not exceed 120 characters.
9.          NEVER type string in code, make it const or enum.
10.      NEVER hard code numeric values (except 0 and 1), instead use const.
11.      Assert every assumption.
12.      Check all parameters validity at the beginning of every method.
13.      Test all scenarios of each method.
14.      Mark types and elements with the least access modifier (use public when needed only).
15.      Avoid using the ternary conditional operator unless in trivial conditions (less readable).
16.      Don’t use public or protected member variables, use properties instead.
17.      Use automatic properties when needed.
18.      Prefer override to new.
19.      Always check for NULL.
20.      Prefer explicit interface implementation (group into region with interface name).
21.      Use String.IsNullOrEmpty() instead of “”.
22.      Use StringBuilder instead of string when building long strings.
23.      Never use goto unless in switch statement.
24.      Implement Dispose when using resources.
25.      Prefer generic classes to their regular alternative.
26.      Treat warnings with HIGH importance like errors.
References:
·   Code Complete (2nd edition)
·   C# Coding Conventions

Comments

Popular posts from this blog

Applying unit test for Redux-Saga with React and Typescript

Redux Containers Unit Testing in React with TypeScript Projects

Applying React and Typescript API Calls unit test using Sinon