code standard
TRANSCRIPT
-
8/13/2019 Code Standard
1/30
C# Coding Standards and Naming Conventions
Below are our C# coding standards, naming conventions, and best practices. Use these in
your own projects and/or adjust these to your own needs.
1. Naming Conventions and Style
douse PascalCasingfor class names and method names.publicclassClientActivity
{
publicvoidClearStatistics()
{
//...
}
publicvoidCalculateStatistics(){
//...
}
}
Why: consistent with the Microsoft's .NET Framework and easy to read.douse camelCasingfor method arguments and local variables.publicclassUserLog
{
publicvoidAdd(LogEventlogEvent)
{
intitemCount = logEvent.Items.Count;// ...
}
}
Why: consistent with the Microsoft's .NET Framework and easy to read.do notuse Hungariannotation or any other type identification in identifiers// Correct
intcounter;
stringname;
// Avoid
intiCounter;stringstrName;
Why: consistent with the Microsoft's .NET Framework and Visual Studio IDE makes determining
types very easy (via tooltips). In general you want to avoid type indicators in any identifier.do notuse Screaming Capsfor constants or readonly variables// Correct
publicstaticconststringShippingType = "DropShip";
// Avoid
publicstaticconststringSHIPPINGTYPE = "DropShip";
Why: consistent with the Microsoft's .NET Framework. Caps grap too much attention.
-
8/13/2019 Code Standard
2/30
avoidusing Abbreviations. Exceptions: abbreviations commonly used as names,such as Id, Xml, Ftp, Uri
// Correct
UserGroupuserGroup;
AssignmentemployeeAssignment;
// Avoid
UserGroupusrGrp;
AssignmentempAssignment;
// Exceptions
CustomerIdcustomerId;
XmlDocumentxmlDocument;
FtpHelperftpHelper;
UriParturiPart;
Why: consistent with the Microsoft's .NET Framework and prevents inconsistent abbreviations. douse PascalCasingfor abbreviations 3 characters or more (2 chars are both uppercase) HtmlHelperhtmlHelper;FtpTransferftpTranfer;
UIControluiControl;
Why: consistent with the Microsoft's .NET Framework. Caps would grap visually too much attention.do notuse Underscoresin identifiers. Exception: you can prefix private static variables
with an underscore.// Correct
publicDateTimeclientAppointment;
publicTimeSpantimeLeft;
// AvoidpublicDateTimeclient_Appointment;
publicTimeSpantime_Left;
// Exception
privateDateTime_registrationDate;
Why: consistent with the Microsoft's .NET Framework and makes code more natural to read (without'slur'). Also avoids underline stress (inability to see underline).douse predefined type namesinstead of system type names like Int16, Single, UInt64, etc
// Correct
stringfirstName;intlastIndex;
boolisSaved;
// Avoid
StringfirstName;
Int32lastIndex;
BooleanisSaved;
Why: consistent with the Microsoft's .NET Framework and makes code more natural to read.
douse implicit type varfor local variable declarations. Exception: primitive types (int, string,double, etc) use predefined names.
varstream = File.Create(path);varcustomers = newDictionary();
-
8/13/2019 Code Standard
3/30
// Exceptions
intindex = 100;
stringtimeSheet;
boolisCompleted;
Why: removes clutter, particularly with complex generic types. Type is easily detected with VisualStudio tooltips.douse noun or noun phrases to name a class.publicclassEmployee
{
}
publicclassBusinessLocation
{
}
publicclassDocumentCollection
{
}
Why: consistent with the Microsoft's .NET Framework and easy to remember.doprefix interfaces with the letter I. Interface names are noun (phrases) or adjectives.publicinterfaceIShape
{
}
publicinterfaceIShapeCollection
{
}
publicinterfaceIGroupable
{
}
Why: consistent with the Microsoft's .NET Framework.doname source files according to their main classes. Exception: file names with partial classes
reflect their source or purpose, e.g. designer, generated, etc.// Located in Task.cs
public partialclassTask
{
//...
}
// Located in Task.generated.cs
public partialclassTask
{//...
}
Why: consistent with the Microsoft practices. Files are alphabetically sorted and partial classes
remain adjacent.doorganize namespaces with a clearly defined structure// Examples
namespace Company.Product.Module.SubModule
namespaceProduct.Module.Component
namespaceProduct.Layer.Module.Group
Why: consistent with the Microsoft's .NET Framework. Maintains good organization of your codebase.
-
8/13/2019 Code Standard
4/30
dovertically align curly brackets.// Correct
classProgram
{
staticvoidMain(string[] args)
{}
}
Why: Microsoft has a different standard, but developers have overwhelmingly preferred verticallyaligned brackets.dodeclare all member variables at the top of a class, with static variables at the very top.// Correct
publicclassAccount
{
publicstaticstringBankName;
publicstaticdecimalReserves;
publicstringNumber {get; set;}
publicDateTimeDateOpened {get; set;}
publicDateTimeDateClosed {get; set;}
publicdecimalBalance {get; set;}
// Constructor
publicAccount()
{
// ...
}
}
Why: generally accepted practice that prevents the need to hunt for variable declarations. douse singular names for enums. Exception: bit field enums.// Correct
publicenumColor
{
Red,
Green,
Blue,
Yellow,
Magenta,
Cyan
}
// Exception
[Flags]
publicenumDockings
{
None = 0,
Top = 1,
Right = 2,
Bottom = 4,
Left = 8
}
Why: consistent with the Microsoft's .NET Framework and makes the code more natural to read.Plural flags because enum can hold multiple values (using bitwise 'OR').
-
8/13/2019 Code Standard
5/30
do notexplicitly specify a type of an enum or values of enums (except bit fields)// Don't
publicenumDirection: long
{
North = 1,
East = 2,South = 3,
West = 4
}
// Correct
publicenumDirection
{
North,
East,
South,
West
}
Why: can create confusion when relying on actual types and values.do notsuffix enum names with Enum// Don't
publicenumCoinEnum
{
Penny,
Nickel,
Dime,
Quarter,
Dollar
}
// Correct
publicenumCoin
{
Penny,
Nickel,
Dime,
Quarter,
Dollar
}
Why: consistent with the Microsoft's .NET Framework and consistent with prior rule of no type
indicators in identifiers.
-
8/13/2019 Code Standard
6/30
Table of Contents
1. Introduction.......................................................................................................................................... 1
2. Style Guidelines.................................................................................................................................... 2
2.1 Tabs & Indenting................................................................................................................................ 2
2.2 Bracing............................................................................................................................................... 2
2.3 Commenting........................................................................................................................................ 2
2.3.1 Documentation Comments............................................................................................................. 2
2.3.2 Comment Style............................................................................................................................. 3
2.4 Spacing............................................................................................................................................... 3
2.5 Naming............................................................................................................................................... 4
2.6 Naming Conventions............................................................................................................................ 4
2.6.1 Interop Classes............................................................................................................................. 4
2.7 File Organization................................................................................................................................. 5
1. Introduction
First, read the .NET Framework Design Guidelines. Almost all naming conventions, casing rules, etc.,
are spelled out in this document. Unlike the Design Guidelines document, you should treat this
document as a set of suggestedguidelines. These generally do not effect the customer view so they
are not required.
2. Style Guidelines2.1 Tabs & Indenting
Tab characters (\0x09) should not be used in code. All indentation should be done with 4 space
characters.2.2 Bracing
Open braces should always be at the beginning of the line after the statement that begins the block.
Contents of the brace should be indented by 4 spaces. For example:
-
8/13/2019 Code Standard
7/30
if (someExpression)
{
DoSomething();
}
else
{DoSomethingElse();
}
case statements should be indented from the switch statement like this:switch (someExpression)
{
case 0:
DoSomething();
break;
case 1:
DoSomethingElse();
break;
case 2:
{
int n = 1;
DoAnotherThing(n);
}
break;
}
Braces should never be considered optional. Even for single statement blocks, you should always use
braces. This increases code readability and maintainability.for (int i=0; i
-
8/13/2019 Code Standard
8/30
It is suggestedthat all control structures (if, while, for, etc.) use braces, but it is not required.2.4 Commenting
Comments should be used to describe intention, algorithmic overview, and/or logical flow. It would
be ideal, if from reading the comments alone, someone other than the author could understand a
functions intended behavior and general operation. While there are no minimum comment
requirements and certainly some very small routines need no commenting at all, it is hoped that
most routines will have comments reflecting the programmers intent and approach.2.4.1 Copyright notice
Each file should start with a copyright notice. To avoid errors in doc comment builds, you dont want
to use triple-slash doc comments, but using XML makes the comments easy to replace in the future.
Final text will vary by product (you should contact legal for the exact text), but should be similar to: //-----------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//-----------------------------------------------------------------------
2.4.2 Documentation Comments
All methods should use XML doc comments. For internal dev comments, the tag should be
used.public class Foo
{
/// Public stuff about the method
/// What a neat parameter!
/// Cool internal stuff!
///
public void MyMethod(int bar) { }
}
However, it is common that you would want to move the XML documentation to an external file
for that, use the tag.public class Foo
{
///
///
public void MyMethod(int bar) { }
}
-
8/13/2019 Code Standard
9/30
UNDONE there is a big doc with all the comment tags we should be using where is that? 2.4.3 Comment Style
The //(two slashes) style of comment tags should be used in most situations. Where ever
possible, place comments above the code instead of beside it. Here are some examples:// This is required for WebClient to work through the proxy
GlobalProxySelection.Select = new WebProxy("http://itgproxy");
// Create object to access Internet resources
//
WebClient myClient = new WebClient();
Comments can be placed at the end of a line when space allows:public class SomethingUseful
{
private int itemHash; // instance member
private static bool hasDoneSomething; // static member
}
2.5 Spacing
Spaces improve readability by decreasing code density. Here are some guidelines for the use ofspace characters within code:
Do use a single space after a comma between function arguments.
Right: Console.In.Read(myChar, 0, 1);
Wrong: Console.In.Read(myChar,0,1);
Do not use a space after the parenthesis and function arguments
Right: CreateFoo(myChar, 0, 1)
Wrong: CreateFoo( myChar, 0, 1 )
Do not use spaces between a function name and parenthesis.
Right: CreateFoo()
Wrong: CreateFoo () Do not use spaces inside brackets.
Right: x = dataArray[index];
Wrong: x = dataArray[ index ];
Do use a single space before flow control statements
Right: while (x == y)
Wrong: while(x==y)
Do use a single space before and after comparison operators
Right: if (x == y)
Wrong: if (x==y)
http://itgproxy/http://itgproxy/http://itgproxy/http://itgproxy/ -
8/13/2019 Code Standard
10/30
2.6 Naming
Follow all .NET Framework Design Guidelines for both internal and external members. Highlights of
these include: Do notuse Hungarian notation
Do notuse a prefix for member variables (_, m_, s_, etc.). If you want to distinguish between local and
member variables you should use this. in C# and Me. in VB.NET.
Douse camelCasing for member variables
Douse camelCasing for parameters
Douse camelCasing for local variables
Do use PascalCasing for function, property, event, and class names
Doprefix interfaces names with I
Do notprefix enums, classes, or delegates with any letter
The reasons to extend the public rules (no Hungarian, no prefix for member variables, etc.) is to
produce a consistent source code appearance. In addition a goal is to have clean readable source.
Code legibility should be a primary goal.2.7 Naming Conventions
2.7.1 Interop Classes
Classes that are there for interop wrappers (DllImport statements) should follow the naming
convention below:
NativeMethodsNo suppress unmanaged code attribute, these are methods that can be usedanywhere because a stack walk will be performed.
UnsafeNativeMethodsHas suppress unmanaged code attribute. These methods are potentially
dangerous and any callerof these methods must do a full security review to ensure that the usage is
safe and protected as no stack walk will be performed.
SafeNativeMethods Has suppress unmanaged code attribute. These methods are safe and can be
used fairly safely and the caller isnt needed to do full security reviews even though no stack walk will be
performed.
class NativeMethods
{
private NativeMethods() {}
[DllImport(user32)]
internal static extern void FormatHardDrive(string driveName);
}
[SuppressUnmanagedCode]
class UnsafeNativeMethods
{
private UnsafeNativeMethods() {}
-
8/13/2019 Code Standard
11/30
[DllImport(user32)]
internal static extern void CreateFile(string fileName);
}
[SuppressUnmanagedCode]
class SafeNativeMethods{
private SafeNativeMethods() {}
[DllImport(user32)]
internal static extern void MessageBox(string text);
}
All interop classes mustbe private, and all methods must be internal. In addition a private
constructor should be provided to prevent instantiation.2.8 File Organization
Source files should contain only one public type, although multiple internal classes are allowed
Source files should be given the name of the public class in the file
Directory names should follow the namespace for the class
For example, I would expect to find the public class System.Windows.Forms.Control in
System\Windows\Forms\Control.cs Classes member should be alphabetized, and grouped into sections (Fields, Constructors, Properties,
Events, Methods, Private interface implementations, Nested types) Using statements should be inside the namespace declaration.
namespace MyNamespace
{
using System;
public class MyClass : IFoo
{
// fieldsint foo;
// constructors
public MyClass() { }
// properties
public int Foo { get { } set { } }
// events
public event EventHandler FooChanged { add { } remove { } }
-
8/13/2019 Code Standard
12/30
// methods
void DoSomething() { }
void FindSomethind() { }
//private interface implementations
void IFoo.DoSomething() { DoSomething(); }
// nested types
class NestedType { }
}
}
-
8/13/2019 Code Standard
13/30
Introduction
Developers always love to fight about coding standards. But it is very vital to follow coding
standards to achieve consistency throughout the project or code. All should be of the same mind
that conventions are very influential. I will show some good practices that I have learned during
my professional years, those are lower level but very important for all levels.
Quick Test
Let us demonstrate a FizzBuzz example. The FizzBuzz test is to write a program that goes through
the numbers 1 to 100. For every multiple of 3, the program should output "Fizz" and for every
multiple of 5 it should output "Buzz". If both above conditions are met it should output
"FizzBuzz". If none of the above conditions are met, it should just output the number.
Example 1:
Collapse |Copy Code
publicvoidTest(){
for(inti = 1; i < 101; i++)
{
if(i % 3== 0&& i % 5== 0)
{Console.WriteLine("FizzBuzz");
}
elseif(i % 3== 0)
{
Console.WriteLine("Fizz");
}
elseif(i % 5== 0)
{
Console.WriteLine("Buzz");
}
else{
Console.WriteLine(i);
}}
http://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-code -
8/13/2019 Code Standard
14/30
}
What do you think? Do we need to make the code better?
Example 2:
Collapse |Copy Code
publicvoidCheck()
{
for(inti = 1; i
-
8/13/2019 Code Standard
15/30
What is better Code?
Write code for People First, Computers Second. Readable code doesn't take any longer to write
than confusing code does, at least not in the long run. Its easier to be sure your code works, if
you can easily read what you wrote. That should be a sufficient reason to write readable code.
But code is also read during reviews. Code is read when you or someone else fixes an error. Code
is read when the code is modified. Code is read when someone tries to use part of your code in a
similar project or different project but similar feature or part of a feature.
What if you just writing code for yourself ? Why should you make it readable ?
Ok, the major reason behind writing readable is , a week or two from now youre going to be
working on another project. What will happen when any other HUMAN needs to fix an error on
that project? I can guarantee you that you will also lost within your own horror code.
From my point of view a better should carried out the following characteristics:
Code that is easy to write , modify and extend
Code that is clean and talks/convey meaning
Code that has values and cares about quality
So, write with the human reader in mind while satisfying the needs of the machine to the degree
necessary.
-
8/13/2019 Code Standard
16/30
How can you improve the Readability?
First you have to read other peoples code and figure out what is good and what is bad within
that code. What makes you easy to understand and what makes you feel more complicated. Then
apply those things to your own code. Finally you need sometime, some experience and you need
some practice to improve the readability of your code. It is very hard but obvious to implement
standards in any software company, through methods like Trainings, Peer Code Reviews,
Introducing automated code review tools, etc. The most popular tools are as follows:
FxCop is a tool that performs static code analysis of .NET code. It provides hundreds of rules that
perform various types of analysis.
StyleCop is an open source project that analyzes C# source code to enforce a set of style and
consistency rules. It can be run from inside of Visual Studio or integrated into an MSBuild project.
StyleCop has also been integrated into many third-party development tools.
JetBrains ReSharperis a renowned productivity tool that makes Microsoft Visual Studio a much
better IDE. Thousands of .NET developers worldwide wonder how theyve ever lived without
ReSharpers code inspections, automated code refactoring, blazing fast navigation, and coding
assistance.
-
8/13/2019 Code Standard
17/30
What are Conventions?
According toWikipedia "Coding conventions are a set of guidelines for a specific programminglanguage that recommend programming style, practices and methods for each aspect of a piece
program written in this language. These conventions usually cover file organization, indentation,
comments, declarations, statements, white space, naming conventions, programming practices,
programming principles, programming rules of thumb, architectural best practices, etc. These are
guidelines for software structural quality. Software programmers are highly recommended to follow
these guidelines to help improve the readability of their source code and make software
maintenance easier. Coding conventions are only applicable to the human maintainers and peer
reviewers of a software project. Conventions may be formalized in a documented set of rules that
an entire team or company follows, or may be as informal as the habitual coding practices of an
individual. Coding conventions are not enforced by compilers. As a result, not following some or all
of the rules has no impact on the executable programs created from the source code."
You should be able to tell the difference between a property, local variable, method name, class
name etc. because they use different capitalization conventions. These type of conventions has
values. You will be able to get lots of guidelines and conventions over internet. So find a
convention or build your own and stick with it.
The source of the following (Design Guidelines for Developing Class Libraries)was developed by
the Microsoft special interest group. I just made some addons.
http://en.wikipedia.org/wiki/Coding_conventionshttp://en.wikipedia.org/wiki/Coding_conventionshttp://en.wikipedia.org/wiki/Coding_conventionshttp://msdn.microsoft.com/en-us/library/ms229042.aspxhttp://msdn.microsoft.com/en-us/library/ms229042.aspxhttp://msdn.microsoft.com/en-us/library/ms229042.aspxhttp://msdn.microsoft.com/en-us/library/ms229042.aspxhttp://en.wikipedia.org/wiki/Coding_conventions -
8/13/2019 Code Standard
18/30
Capitalization Conventions
Below are some examples of our C# coding standards, naming conventions, and best practices.
Use these according to your own needs.
Pascal Casing
The first letter in the identifier and the first letter of each subsequent concatenated word are
capitalized. You can use Pascal case for identifiers of three or more characters.
Camel Casing
The first letter of an identifier is lowercase and the first letter of each subsequent concatenated
word is capitalized.
Ref.Capitalization Rules for Identifiers
Examples of Some Naming Conventions Guidelines
You will find enough resources over internet. I am just highlighting some of my favorites among
them
C# Coding Conventions
C# Coding Guidelines
C# Coding Standards and Best Programming Practices
C# Coding Standards and Naming Conventions
I am providing some basic level examples below but as I already mentioned, find a good
convention that fits for you and stick with it.
Douse PascalCasing for class names and method names.
http://msdn.microsoft.com/en-us/library/ms229043.aspxhttp://msdn.microsoft.com/en-us/library/ms229043.aspxhttp://msdn.microsoft.com/en-us/library/ms229043.aspxhttp://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspxhttp://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspxhttp://csharpguidelines.codeplex.com/http://csharpguidelines.codeplex.com/http://www.dotnetspider.com/tutorials/BestPractices.aspxhttp://www.dotnetspider.com/tutorials/BestPractices.aspxhttp://www.dofactory.com/reference/csharp-coding-standards.aspxhttp://www.dofactory.com/reference/csharp-coding-standards.aspxhttp://www.dofactory.com/reference/csharp-coding-standards.aspxhttp://www.dotnetspider.com/tutorials/BestPractices.aspxhttp://csharpguidelines.codeplex.com/http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspxhttp://msdn.microsoft.com/en-us/library/ms229043.aspx -
8/13/2019 Code Standard
19/30
Collapse |Copy Code
publicclassProduct{
publicvoidGetActiveProducts()
{
//...}publicvoidCalculateProductAdditinalCost()
{
//...
}
}
Douse camelCasing for method arguments and local variables.
Collapse |Copy Code
publicclassProductCategory{publicvoidSave(ProductCategory productCategory)
{
// ...
}
}
Do notuse Abbreviations.
Collapse |Copy Code
// CorrectProductCategory productCategory;
// Avoid
ProductCategory prodCat;
Do notuse Underscores in identifiers.
Collapse |Copy Code
// Correct
ProductCategoryproductCategory;
// Avoid
ProductCategoryproduct_Category;
Doprefix interfaces with the letter I.
Collapse |Copy Code
publicinterfaceIAddress{
}
http://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-code -
8/13/2019 Code Standard
20/30
Dodeclare all member variables at the top of a class, with static variables at the very top.
Collapse |Copy Code
publicclass Product
{ publicstatic string BrandName;
publicstring Name{get; set;}
publicDateTimeDateAvailable {get; set;}
publicProduct()
{
// ...
}
}
Douse singular names for enums. Exception: bit field enums.
Collapse |Copy Code
publicenumDirection{
North,
East,
South,
West
}
Do notsuffix enum names with Enum.
Collapse |Copy Code
//Avoid
publicenumDirectionEnum
{
North,
East,
South,
West
}
Why We Need Conventions?
Programmers on large projects sometimes go overboard with conventions. They establish so
many standards and guidelines that remembering them becomes a full-time job. The computer
doesnt care whether your code is readable. Its better at reading binary machine instructions
than it is at reading high-level-language statements.
Conventions offer several specific benefits. They let you take more for granted. By making one
global decision rather than many local ones, you can concentrate on the more important
characteristics of the code.
http://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-code -
8/13/2019 Code Standard
21/30
They help you transfer knowledge across projects
They help you learn code more quickly on a new project.
They emphasize relationships among related items.
You should write readable code because it helps other people to read your code. Naming thing is
one of the hardest job we have as a software developer. Because we spend a lot of time namingthings, there are so many things to name properties, methods, classes, files, projects etc. We
should spend some energies for naming things because names can be meanings. Adding
meaning to code is readability all about.
So it will help you better sleep at night.
Top Rules Developers Should Follow
Keep Class Size Small
I have seen and written some gigantic classes. But unfortunately those were never turns out well.
Later I found the reason that is, those large classes try to do too many things. That violates the
Single Responsibility Principle. SinSOLID (Object Oriented Design).
Thesingle responsibility principle states that every object should have a single responsibility, and
that responsibility should be entirely encapsulated by the class. All its services should be narrowly
aligned with that responsibility.
http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29 -
8/13/2019 Code Standard
22/30
Or
According toMartinsdefinition:"THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A
CLASS TO CHANGE."
Why was it important to separate these two responsibilities into separate classes? Because eachresponsibility is an axis of change. When the requirements change, that change will be manifest
through a change in responsibility amongst the classes. If a class assumes more than one
responsibility, then there will be more than one reason for it to change. If a class has more then
one responsibility, then the responsibilities become coupled. Changes to one responsibility may
impair or inhibit the class ability to meet the others. This kind of coupling leads to fragile designs
that break in unexpected ways when changed.
Avoid Obsolete Comments
Let us start with Obsolete Comments. According toRobert C. Martin:
"A comment that has gotten old, irrelevant, and incorrect is obsolete. Comments get old quickly. It
is best not to write a comment that will become obsolete. If you find an obsolete comment, it is
best to update it or get rid of it as quickly as possible. Obsolete comments tend to migrate away
from the code they once described. They become floating islands of irrelevance and misdirection in
the code."
This is topic create some interesting conversations among all level of developers. Try to avoid
comments on individual method or short class. Because most comments i have ever seen is trying
to describe the purpose/intentions. Some cases comments are meaningless. Developers writes
comments to increase the readability & maintainability . Make sure your comments are notmaking any noise. It will be great if you could name a method more meaningful instead of
http://www.objectmentor.com/resources/articles/srp.pdfhttp://www.objectmentor.com/resources/articles/srp.pdfhttp://www.objectmentor.com/resources/articles/srp.pdfhttp://www.objectmentor.com/resources/articles/srp.pdfhttp://en.wikipedia.org/wiki/Robert_Cecil_Martinhttp://en.wikipedia.org/wiki/Robert_Cecil_Martinhttp://en.wikipedia.org/wiki/Robert_Cecil_Martinhttp://en.wikipedia.org/wiki/Robert_Cecil_Martinhttp://www.objectmentor.com/resources/articles/srp.pdf -
8/13/2019 Code Standard
23/30
comments. I am suggesting because method names are more affective than comments. Most of
the comments are meaningless noise. Let us check comments below:
Collapse |Copy Code
//ensure that we are not exporting//deleted products
if(product.IsDeleted && !product.IsExported ){
ExportProducts = false;
}
// This is a for loop that prints the 1 million times
for(inti = 0; i < 1000000; i++){
Console.WriteLine(i);
}
If we name the method like CancelExportForDeletedProducts()instead of comments whatwill happen? So, method names are more affective than comments. Methods execute and they
are real. But comment is good for some cases like, when visual studio will take comments for
creating an API documentation and those comments are different, you can use "///" for those
comments so that other developers can get intelligence of API or Library.
I am nottelling you that avoid comment is a must for all the times. According to Kent's oral
tradition point goes more to large-scale comments about how the whole thing works, not to
individual method comments. If comment is trying to describe the purpose/intentions then it is
wrong. If you look at thickly commented code, you will notice that most of those comments are
there because the code is bad. Please read the following books for further detail:
Professional Refactoring in C# and ASP.NETby Danijel Arsenovski
"Refactoring: Improving the Design of Existing Code" byMartin Fowler, Kent Beck,John
Brant, William Opdyke, don Roberts
Avoid Unnecessary Regions in Class
Regions are a feature of VS that allow you to surround blocks of code. It could be a single or
multiple methods. The region exists because it is easier to navigate around the large file. The
regions are used to hide ugly code or class that have exploded in size . If a class does too many
things it also violates the Single Responsibility Principle. So next time whenever you will think foradding a new region to your file take step back and ask that is it possible to separate your region
into a separate class.
Keep Method Short
The more lines of code in a method the harder it is to understand. Everyone recommends 20-25
lines of code is ok. But some geeks prefer 1-10 lines for safety, this their personal preference.
There is no hard and fast rule. Extract Method is one of the most common refactoring. If you
consider a method that is too long or needs a comment to understand its purpose. You can
apply Extract Method there with little effort. People always keep asking on the length for a
method. But length is not the issue. When you are dealing with complex methods, keeping trackof all local variables can be complicated and time-consuming. Where extracting a method can be
http://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-code -
8/13/2019 Code Standard
24/30
a real time-saver. You can use the Visual Studio extract method which will track which variables
are passed to a new method, which are returned by the methods return value as output
parameters.
Using ReSharper
Using Microsoft Visual Studio
For more detail on each step, please navigate theMSDN link.
According to Refactoring: Improving the Design of Existing Code by Martin Fowler, Kent
Beck (Contributor), John Brant (Contributor), William Opdyke, don Roberts
http://msdn.microsoft.com/en-us/library/0s21cwxk.aspxhttp://msdn.microsoft.com/en-us/library/0s21cwxk.aspxhttp://msdn.microsoft.com/en-us/library/0s21cwxk.aspxhttp://msdn.microsoft.com/en-us/library/0s21cwxk.aspx -
8/13/2019 Code Standard
25/30
"Extract Method is one of the most common refactoring I do. I look at a method that is too long or
look at code that needs a comment to understand its purpose. I then turn that fragment of code
into its own method. I prefer short, well-named methods for several reasons. First, it increases the
chances that other methods can use a method when the method is finely grained. Second, it allows
the higher-level methods to read more like a series of comments. Overriding also is easier when the
methods are finely grained. It does take a little getting used to if you are used to seeing largermethods. And small methods
really work only when you have good names, so you need to pay attention to naming. People
sometimes ask me what length I look for in a method. To me length is not the issue. The key is the
semantic distance between the method name and the method body. If extracting improves clarity,
do it, even if the name is longer than the code you have extracted."
Avoid Too Many Parameters
Declare a class instead of too many parameters. Creating a class that puts all these parameters
together. This is generally a better design and valuable abstraction.
Collapse |Copy Code
//avoid
publicvoidCheckout(stringshippingName, stringshippingCity,stringshippingSate, stringshippingZip, stringbillingName,
stringbillingCity, stringbillingSate, stringbillingZip)
{
}
Collapse |Copy Code
//DO
publicvoidCheckout(ShippingAddress shippingAddress,BillingAddress billingAddress)
{
}
We should introduce class instead of all parameters.
Avoid Complex ExpressionsCollapse |Copy Code
if(product.Price>500&& !product.IsDeleted &&!product.IsFeatured && product.IsExported){
// do something
}
Complex expression have some meaning behind them it is just hidden by those multiple
expressions. We can encapsulate the complex expression into that object by using a property.
That code will be easier to read.
http://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-code -
8/13/2019 Code Standard
26/30
Consider Warnings as Errors
If you notice the code you will find a variable that was declared but never used. Normally if we
build the project we will get a warning and we can run our project without any error. But we
should remove warning as much as possible. So setup your build to treat warning as Errors like
the following steps:
-
8/13/2019 Code Standard
27/30
Minimize the Number of Returns
Minimize the number of returns in each routine. It's harder to understand a routine if, reading it
at the bottom, you're unaware of the possibility that it returned somewhere above.
Use a return when it enhances readability. In certain routines, once you know the answer, you
want to return it to the calling routine immediately. If the routine is defined in such a way that it
doesn't require any cleanup, not returning immediately means that you have to write more code.
Collapse |Copy Code
http://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-code -
8/13/2019 Code Standard
28/30
//avoid
if(product.Price>15)
{returnfalse;
}
elseif(product.IsDeleted)
{returnfalse;
}
elseif(!product.IsFeatured)
{
returnfalse;
}
elseif(){
//.....
}
returntrue;
Collapse |Copy Code
//DO
varisValid = true;
if(product.Price>15)
{isValid= false;
}
elseif(product.IsDeleted)
{
isValid= false;
}
elseif(!product.IsFeatured)
{
isValid= false;
}returnisValid;
You can imagine 4 exit points scattered around 20- 30 lines of code. That makes you more harder
to understand and see what is happening inside the method and what will execute and when will
execute.
I got too many responses, some agreeing but mostly disagreeing that it was a good "standard"
to enforce. To find out the potentiality I did some unit testing and found that for complex
method that have multiple exit points usually have a set of tests for each of those paths.
Collapse |Copy Code
if( BADFunction() == true)
{
// expression
if( anotherFunction() == true){
// expression
returntrue;
}
else
{//error
}}
else
http://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-code -
8/13/2019 Code Standard
29/30
{
//error
}
returnfalse;
Collapse |Copy Code
if( !GoodFunction())
{// error.
returnfalse
}
// expression
if( !GoodFunction2()){
//error.
returnfalse;
}
// more expression
returntrue;
Ref. "Code Complete" by Steve McConnellfor further detail clarification.
Move Declaration Near Reference
Some programmers are used to placing temporary variable declarations at the top of the
method.But by placing the variable declaration far away from the line where it is first referenced,
you are making code more difficult to read, because it is not immediately clear how the variable
was initialized. In addition, declaring variables well ahead of time makes the method more
difficult to refactor. If you try to extract a part of the method in which the variable was
referenced, you have to pass the variable as a parameter to a newly extracted method, eventhough the declaration could possibly have been placed inside the extracted block.
Assertion
An assertion is code thats used during developmentusually a routine or macrothat allows to
check itself as it runs. True means everything is operating as expected. False means it has
detected an unexpected error in the code. An assertion usually takes two arguments: a Boolean
expression that describes the assumption thats supposed to be true and a message to display if
it isnt.
Assertions are especially useful in large, complicated and in high reliability system.
Example: If a system assumes that there will be maximum 100,000 user records, the system might
contain an assertion that the number of records is less than or equal to 100,000. So assertion will
be silent within that range. If it encounters more than that records, it will loudly assert that
there is an error in the program.
Checking Loop Endpoints
A single loop usually has three cases of interest: the first case, an arbitrarily selected middle case,
and the last case. If you have any special cases that are different from the first or last case, check
http://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-codehttp://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-code -
8/13/2019 Code Standard
30/30
those too. If the loop contains complex computations, get out your calculator and manually
check the calculations.
Conclusion
It is obvious to implement standards in any software company according to organizational
behavior, project nature, and domain. So I would like to repeat "Find a convention and stick with
it".
If you think I missed any prominent guideline, please leave that in the comments section. Ill try
to include that in the main post. Coding For Fun.