best practices for Good programming

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:

  • the opening comment

  • the package statement

  • the import statements

  • the class and interface declaration

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.


2.1.6.1Capitalization Styles

Describes the Pascal case, camel case, and uppercase capitalization styles to use to name identifiers in class libraries.


  • Pascal case


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







  • Camel case


The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized.

Example:


backColor





  • Uppercase


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


  • Do not use names that require case sensitivity. Components must be fully usable from both case-sensitive and case-insensitive languages.


  • Case-insensitive languages cannot distinguish between two names within the same context that differ only by case. Therefore, you must avoid this situation in the components or classes that you create.


  • Do not create two namespaces with names that differ only by case. For example, a case insensitive language cannot distinguish between the following two namespace declarations.

namespace ee.cummings;

namespace Ee.Cummings;







  • Do not create a function with parameter names that differ only by case. The following example is incorrect.


void MyFunction(string a, string A)





  • Do not create a namespace with type names that differ only by case. In the following example, Point p and POINT p are inappropriate type names because they differ only by case.

System.Windows.Forms.Point p


System.Windows.Forms.POINT p







  • Do not create a type with property names that differ only by case. In the following example,

int Color and int COLOR are inappropriate property names because they differ only by case.

int Color

{

get, set

}


int COLOR

{

get, set

}














  • Do not create a type with method names that differ only by case. In the following example, calculate and Calculate are inappropriate method names because they differ only by case.

void calculate()


void Calculate()








2.1.6.3Abbreviations


  • To avoid confusion and guarantee cross-language interoperation, follow these rules regarding the use of abbreviations:


  • Do not use abbreviations or contractions as parts of identifier names.

Example:


Good:

GetWindow


Not Good:

GetWin









  • Do not use acronyms that are not generally accepted in the computing field.


  • Where appropriate, use well-known acronyms to replace lengthy phrase names. For example, use UI for User Interface and OLAP for On-line Analytical Processing.


  • 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

  • Use a noun or noun phrase to name a class.


  • Use Pascal case.


  • Use abbreviations sparingly.


  • 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.


  • Do not use the underscore character (_).


  • Where appropriate, use a compound word to name a derived class. The second part of the derived class's name should be the name of the base class. Example : ApplicationException

public class FileStream


public class Button


public class String









  • Do not use the base word to access base class members unless you wish to resolve a conflict with subclasses member of the same name or when invoking base class constructors.


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:


  • Name interfaces with nouns or noun phrases, or adjectives that describe behaviour.

Example:

IComponent // noun.

ICustomAttributeProvider //noun.

IPersistable //adjective.







  • Use Pascal case.


  • Use abbreviations sparingly.


  • Prefix interface names with the letter I, to indicate that the type is an interface.


  • Use similar names when you define a class/interface pair where the class is a standard implementation of the interface. The names should differ only by the letter I prefix on the interface name.


  • Do not use the underscore character (_).


  • Always user Interfaces.



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.

}













  • Classes and interfaces should have at least 2:1 ratio of methods to properties.


  • Avoid interfaces with one method.


  • No more than 20 members per interface.


  • Avoid event as interface members.


  • Avoid abstract methods, user interfaces instead.

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


  • The enumeration (Enum) value type inherits from the Enum Class.

    • Use Pascal case for Enum types and value names.

    • Use abbreviations sparingly.


    • Do not use an Enum suffix on Enum type names.


    • Use a singular name for most Enum types, but use a plural name for Enum types that are bit fields.


    • Always add the FlagsAttribute to a bit field Enum type.


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

  • Naming guidelines for static fields:


    • Use nouns, noun phrases, or abbreviations of nouns to name static fields.


    • Use Pascal case.


    • Do not use a Hungarian notation prefix on static field names.


    • It is recommended that you use static properties instead of public static fields whenever possible.


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 camel case for parameter names.


  • Use descriptive parameter names. Parameter names should be descriptive enough that the name of the parameter and its type can be used to determine its meaning in most scenarios.


  • 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.


  • Do not use reserved parameters.


  • Do not prefix parameter names with Hungarian type notation.


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:


  • Use verbs or verb phrases to name methods.


  • Use Pascal case


Examples: Correctly named methods.


RemoveAll()


GetCharArray()


Invoke()









2.1.6.12Property Naming Guidelines

The following rules outline the naming guidelines for properties:


  • Use a noun or noun phrase to name properties.


  • Use Pascal case.


  • Do not use Hungarian notation.


  • Consider creating a property with the same name as its underlying type.


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:

  • Use Pascal case.


  • Do not use Hungarian notation.


  • Use an EventHandler suffix on event handler names.


  • Specify two parameters named sender and e.


    • The sender parameter represents the object that raised the event. The sender parameter is always of type object.


    • The state associated with the event is encapsulated in an instance of an event class named e. Use an appropriate and specific event class for the e parameter type.


  • Name an event argument class with the EventArgs suffix.


  • Consider naming events with a verb. For example, correctly named event names include Clicked, Painting, and DroppedDown.


  • Do not use a prefix or suffix on the event declaration on the type. For example, use Close instead of OnClose.


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:


  • Use Pascal case.


  • Do not use Hungarian notation.


  • Copy a delegate to local variable before publishing to avoid concurrency race condition.


  • Always check a delegate for null before invoking it.


  • Use delegate inference instead of explicit delegate instantiation



delegate void SomeDegate();


public void SomeMethod()

{

//Code goes here.

}


SomeDelegate someDelegate = SomeMethod;











2.1.7Use Early Binding for Better performance


  • Early Binding provides much better performance than late binding.


  • Always specify a data type for variables when they are declared. This provides strong typing of variables for best 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

  • Never use goto unless in a switch statement fall through.


  • Always have a default case in a switch statement that asserts.




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();

}

















Listen to nirmaln - sakara - playlist audio songs at MusicMazaa.com