best practices for Good programming
2.1.1Avoid having too large files.
If a file has more than 300~400 lines of code, you must consider refactoring code into helper classes.
2.1.2Avoid 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.1.3White Space
Blank lines improve readability by setting off sections of code that are logically related.
Two blank lines should always be used between sections of a source file. That is, two blank lines should follow:
One blank line should always be used in the following circumstances:
Between methods
Between the local variables in a method and its first statement
Before a block or single-line comment.
Between logical sections inside a method to improve readability.
Use common sense and don't be afraid to put blank lines!
2.1.4Blank Spaces
Blank spaces should be used in the following circumstances:
A blank space should appear after commas in argument lists.
All binary operators except. Should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment ("++"), and decrement ("--") from their operands.
The expressions in a "for" statement should be separated by blank spaces.
example:
public void aMethod(int a, int b, int c, int d)
{
a += c + d;
a = (a + b) / (c * d);
printSize("size is " + foo);
for(expr1; expr2; expr3)
{
/* No Body */
}
}
2.1.5Parentheses
It is generally a good idea to use parentheses liberally in expressions involving mixed operators to avoid operator precedence problems
if(a == b && c == d) // AVOID!
if((a == b) && (c == d)) // RIGHT
2.1.6Naming Guidelines
A consistent naming pattern is one of the most important elements of predictability and discoverability in a managed class library.
Describes the Pascal case, camel case, and uppercase capitalization styles to use to name identifiers in class libraries.
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.
Example:
BackColor
The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized.
Example:
backColor
All letters in the identifier are capitalized. Use this convention only for identifiers that consist of two or fewer letters.
Example:
Sysetm.IO
System.Web.UI
The following table summarizes the capitalization rules and provides examples for the different types of identifiers:
-
| Identifier | Case | Example |
| Class | Pascal | AppDomain |
| Enum type | Pascal | ErrorLevel |
| Enum values | Pascal | FatalError |
| Event | Pascal | ValueChange |
| Exception class | Pascal | WebException Note Always ends with the suffix Exception. |
| Read-only Static field | Pascal | RedValue |
| Interface | Pascal | IDisposable Note Always begins with the prefix I. |
| Method | Pascal | ToString |
| Namespace | Pascal | System.Drawing |
| Parameter | Camel | typeName |
| Property | Pascal | BackColor |
| Protected instance field | Camel | redValue Note Rarely used. A property is preferable to using a protected instance field. |
| Public instance field | Pascal | RedValue Note Rarely used. A property is preferable to using a public instance field. |
2.1.6.2Case Sensitivity
namespace ee.cummings;
namespace Ee.Cummings;
void MyFunction(string a, string A)
System.Windows.Forms.Point p
System.Windows.Forms.POINT p
int Color and int COLOR are inappropriate property names because they differ only by case.
int Color
{
get, set
}
int COLOR
{
get, set
}
void calculate()
void Calculate()
2.1.6.3Abbreviations
Example:
Good:
GetWindow
Not Good:
GetWin
When using acronyms, use Pascal case or camel case for acronyms more than two characters long. For example, use HtmlButton or htmlButton. However, you should capitalize acronyms that consist of only two characters, such as System.IO instead of System.Io.
Do not use abbreviations in identifiers or parameter names. If you must use abbreviations, use camel case for abbreviations that consist of more than two characters, even if this contradicts the standard abbreviation of the word.
2.1.6.4Namespace Naming Guidelines
You should use Pascal case for namespaces
T CompanyName.TechnologyName[.Feature][.Design]
For example:
Microsoft.Media
Microsoft.Media.Design
he general rule for naming namespaces is to use the company name followed by the technology name and optionally the feature and design as follows.
2.1.6.5Class Naming Guidelines
Do not use a type prefix, such as C for class, on a class name. For example, use the class name FileStream rather than CFileStream.
public class FileStream
public class Button
public class String
public class Dog
{
public Dog ( string name )
{ }
virtual public void Bark ( int howLong )
{}
}
public class GermanShepherd : Dog
{
public GermanShepherd( string name ) : base( name )
{}
override public void Bark( int howLong )
{
base.Bark( howLong )
}
}
2.1.6.6Interface Naming Guidelines
The following rules outline the naming guidelines for interfaces:
Example:
IComponent // noun.
ICustomAttributeProvider //noun.
IPersistable //adjective.
Example:
The following are examples of correctly named interfaces.
public interface IServiceProvider
public interface IFormatable
The following code example illustrates how to define the interface IComponent and its standard implementation, the class Component.
public interface IComponent
{
// Implementation goes here.
}
public class Component: IComponent
{
// Implementation code goes here.
}
2.1.6.7Attribute Naming Guidelines
You should always add the suffix Attribute to custom attribute classes.
Example:
public class ObsoleteAttribute{}
2.1.6.8Enumeration Type Naming Guidelines
Example:
Good:
public enum Color
{
Red, Green, Blue
}
Not Good:
Public enum Color
{
Red = 1, Green = 2, Blue = 3
}
Specifying type for an enum
Not Good:
public enum Color : long
{
Red, Green, Blue
}
2.1.6.9Static Field Naming Guidelines
Example:
public static int Global1 = 100;
public static int Global1 = 200;
2.1.6.10Parameter Naming Guidelines
It is important to carefully follow these parameter naming guidelines because visual design tools that provide context sensitive help and class browsing functionality display method parameter names to users in the designer.
Use names that describe a parameter's meaning rather than names that describe a parameter's type. Development tools should provide meaningful information about a parameter's type. Therefore, a parameter's name can be put to better use by describing meaning. Use type-based parameter names sparingly and only where it is appropriate.
Example: correctly named parameters
Type GetType(string typeName)
string Format(string format, object[] args)
2.1.6.11Method Naming Guidelines
The following rules outline the naming guidelines for methods:
Examples: Correctly named methods.
RemoveAll()
GetCharArray()
Invoke()
2.1.6.12Property Naming Guidelines
The following rules outline the naming guidelines for properties:
Example:
Good:
1) public class smapleClass
{
public color BackColor
{
//Code for get and set assessors goes here.
}
}
2) Providing a property with the same name as a type.
public enum Color
{
// Insert code for Enum here.
}
public class Control
{
public Color Color
{
get {// Insert code here.}
set {// Insert code here.}
}
}
Not Good:
public enum Color
{
// Insert code for Enum here.
}
public class Control
{
public int Color
{
get {// Insert code here.}
set {// Insert code here.}
}
}
This is incorrect because the property Color is of type Integer.
2.1.6.13Event Naming Guidelines
The naming guidelines for events:
Consider naming events with a verb. For example, correctly named event names include Clicked, Painting, and DroppedDown.
Example: Illustrates an event handler with an appropriate name and parameters.
public delegate void MouseEventHandler(object sender, MouseEventArgs e);
Example: Illustrates a correctly named event argument class.
public class MouseEventArgs : EventArgs
{
int x;
int y;
public MouseEventArgs(int x, int y)
{
this.x = x; this.y = y;
}
public int X { get { return x; } }
public int Y { get { return y; } }
}
2.1.6.14Delegate Naming Guidelines
The naming guidelines for events:
delegate void SomeDegate();
public void SomeMethod()
{
//Code goes here.
}
SomeDelegate someDelegate = SomeMethod;
2.1.7Use Early Binding for Better performance
Good:
Early Binding
String[] address = null;
Not Good:
Late Binding
Object[] address = null;
2.1.8Returning Values
Try to make the structure of your program match the intent. Example:
if(booleanExpression)
{
return true;
}
else
{
return false;
}
should instead be written as
return booleanExpression;
Similarly,
if(condition)
{
return x;
}
return y;
should be written as
return ((condition) ? x : y);
2.1.9Statements
2.1.9.1Simple Statements
argv++; /* Correct */
argc--; /* Correct */
argv++; argc--; /* AVOID! */
2.1.9.2Compound Statements
Compound statements are statements that contain lists of statements enclosed in braces
"{ statements }".
The enclosed statements should be indented one more level than the enclosing braces.
The opening brace should be at the beginning of the line that precedes the compound statement; the closing brace should begin a line and be indented to the opening brace.
Braces are used around all statements, even single statements, when they are part of a control structure, such as an if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.
2.1.9.3if, if-else, if else-if else Statements
The if-else class of statements should have the following form:
if(condition)
{
statements;
}
if(condition)
{
statements;
}
else
{
statements;
}
if(condition)
{
statements;
}
else if(condition)
{
statements;
}
else
{
statements;
}
Note: if statements always use braces {}. Avoid the following error-prone form:
if(condition) /* AVOID! THIS OMITS THE BRACES {}! */
statement;
2.1.9.4for Statements
A for statement should have the following form:
for(initialization; condition; update)
{
statements;
}
An empty for statement (one in which all the work is done in the initialization, condition, and update clauses) should have the following form:
for(initialization; condition; update)
{
/* No Body */
}
When using the comma operator in the initialization or update clause of a "for" statement, avoid the complexity of using more than three variables.
If needed, use separate statements before the "for" loop (for the initialization clause) or at the end of the loop (for the update clause).
2.1.9.5while Statements
A while statement should have the following form:
while(condition)
{
statements;
}
An empty while statement should have the following form:
while(condition)
{
/* No Body */
}
2.1.9.6do-while Statements
A do-while statement should have the following form:
do
{
statements;
}
while(condition);
2.1.9.7switch Statements
A switch statement should have the following form:
switch(condition)
{
case ABC:
statements;
/* falls through */
case DEF:
statements;
break;
case XYZ:
statements;
break;
default:
statements;
break;
}
2.1.9.8Using Statement
Works with any IDisposable object
Data access classes, streams, text readers and writers, network classes, etc.
Good:
using (Resource res = new Resource()) {
res.DoWork();
}
Not Good:
Resource res = new Resource(...);
try {
res.DoWork();
}
finally {
if (res != null) ((IDisposable)res).Dispose();
}