coding standards

21
Coding Standards

Upload: naomi

Post on 28-Jan-2016

31 views

Category:

Documents


0 download

DESCRIPTION

Coding Standards. Do conventions make difference in functionality?. X1 = X1 - X2 XX = X2+ST( fi ); X1 = X1 + LF(X1, X2) + XX X1 = X+ IT(X1, X);. OR balance = balance - lastPayment monthlyTotal = newPurchase+SalesTax(newPurchase); - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Coding Standards

Coding Standards

Page 2: Coding Standards

Do conventions make difference in functionality?

X1 = X1 - X2

XX = X2+ST( fi );

X1 = X1 + LF(X1, X2) + XX

X1 = X+ IT(X1, X);

OR

balance = balance - lastPayment

monthlyTotal = newPurchase+SalesTax(newPurchase);

Balance= balance + LateFee(customer, balance) + monthlyTotal;

balance = balance+ Interest(customerId, balance);

Page 3: Coding Standards

Naming variables

Too short

Ok Too long

c checkTotal theTotalDollarAmountOfTheCurrentCheck

lp linesPerPage theNumberOfLinesInTheCurrentPage

Page 4: Coding Standards

Naming methods

t1 = calc1();

t2 = calc2();

S2 = calcAll(t1, t2);

netPrice = CalculatePrice();

tax = CalculateTax();

sum = CalculateSum(netPrice, tax);

Page 5: Coding Standards

are comments the answer?

// the total to = 0.0;// looping on line items// lt is total number of lines for( int i = 0 ; i < lt ; i++){

// adding line to totalto = to + li(i);

}

total = 0.0 for (int line = 0 ; lines <linesTotal ; line++){

total = total + LineValue(line);}

Page 6: Coding Standards

“Any convention is better than no convention. The power of naming convention doesn’t come from the specific convention chosen but from the fact that a convention exists, adding structure to the code and

giving you fewer things to worry about”

Steve McConnell, Code Complete.

Page 7: Coding Standards

“Actual” Examples of hard to maintain code

• InterChange.cs in the transactioSet.dll 7,059 lines of Code comparing to the consesus maximum of 300~400.

• DeisgnerForm in the FormDesigner is 3,866 lines of code • BCC’s CalculateHcfa method:

– 900 lines of code in ONE method– More than 50 local variables declared

• Reading from a workflow message:

if(((Kernel.PharmacyDl.PharmacyDl_Service_Lines_Loop)hMsg.L4_PharmacyDl_Service_Lines_Loop[piLineNo-1]).S1_Service_Lines_Segment.Count > 0){

((Kernel.PharmacyDl.Service_Lines_Segment)((Kernel.PharmacyDl.PharmacyDl_Service_Lines_Loop)hMsg.L4_PharmacyDl_Service_Lines_Loop[piLineNo-1]).S1_Service_Lines_Segment[0]).E18_Accepted_Flag.ElementValue = psValue;}

Page 8: Coding Standards

When you should NOT care about sticking to a convention?

• When you are sure no one else except you will ever have to work with that code.

• When program is so small that you can remember all details in your head.

• When you want the programmers working with you to be mad.

Page 9: Coding Standards

Coding Guidelines consist of:

• Naming guidelines: How to name namespaces/Classes/Methods/Properties/Variables,…

• Programming Guidelines: raising and handling exceptions, class size, method size, best practices,..

Page 10: Coding Standards

Naming Guidelines

Main Capitalization styles in .NET:• Pascal case

The first letter in the identifier and the first letter of each subsequent concatenated word are capitalized. For example: BackColor

• Camel caseThe first letter of an identifier is lowercase

and the first letter of each subsequent concatenated word is capitalized. For example: backColor

Page 11: Coding Standards

Naming Guidelines

General considerations:• Do NOT use abbreviations: GetPatient vs. GetPat

• Do NOT use underscores.

• Use Correctly spelled words

• Avoid homonyms: IQ vs. EYEQ

• NEVER use a single character variable unless as loop index.

• Camel case for parameters and local variables.

• Pascal Case for properties, Methods and Classes.

• Always use CLEAR names that suggest the use of the field/prop./method/class.

• Use only IT related acronyms: UI vs. GPC (which is a “known” acronym)

• Research suggests that planning to use conventions after a “fast start” without conventions rarely works.

Page 12: Coding Standards

Programming Guidelines

• Keep It Simple. The key point is to manage complexity.

• You should be alarmed if– Class is more than 300~400 lines.– Method is more than 25 lines.– Ambiguous method names: getNum vs. GetPhoneNumber– Numbers are hardcode numbers. Use constants instead.

– Strings/Paths/Messages are hardcoded. Use resource files instead.

– Vague Error messages: Error in application vs. Error accessing DB.

Page 13: Coding Standards

Dealing with Exceptions

• Methods should throw exceptions rather than return an error code.

• Provide a method to check the condition to avoid the exception:– Example: provide a method IsFileExisting() so users will use it before LoadFile().

• Always throw the specific exception not the general Exception

• Never use an empty catch

• Always catch the specific exception

• Stack Trace starts where exception is thrown not where is occurred:– Example:– Try– { some code causing exception}– Catch– {– Throw new exception vs. throw– }

Page 14: Coding Standards

Best Practices

Always check the parameters at the beginning of the method. Rather than letting the problem propagate and make debugging much harder

Example:

Public void CheckClientAgeAtServiceDate(String name)

{

// code to get Client Data from DB

// code to get service Data from DB

String firstName = name.Substring(0); ---may throw null reference exception

}

Page 15: Coding Standards

Best Practices

Logging saves a lot of time in debugging:

Example:Public void CalculateCartValue(){

int numberOfItems = GetNumberOfItems();log(“number of items = “ + numberOfItems);

for ( int I = 0 ; I < numberOfItems; i++){itemPrice = GetItemPrice(i);log(“price of item = “ + I +” is “itemPrice );}

}

Page 16: Coding Standards

Best Practices StringBuilder(dynamic) vs. String (immutable)

Bad Example:String x = “”;

For (int I = 0 ; I < 100 ; i++)

{

x = (String)array[i];

}

Creates 100 Object

• Good Example:StringBuilder x = new StringBuilder(“”)

For (int I = 0 ; I < 100 ; i++)

{

x = (String)array[i];

}

Creates 1 Object

Page 17: Coding Standards

Best Practicesusing Constants rather than literal strings

• Bad

String name = (String)hashtable(“name”);

Or

int columnId = dataReader.getOrdinal(“Name”);

• Good

Const string NameKey = “name”;

String name = (String)hashtable(NameKey);

Or

int columnId = dataReader.getOrdinal(NameKey);

Page 18: Coding Standards

Tools

• FxCop: http://www.gotdotnet.com/team/fxcop/

• FxCop is an application that analyzes managed code assemblies and reports information about the assemblies, such as possible design, localization, performance, naming, design rules and security improvements.

• FxCop is FREE.

• Available as standalone and built in VS 2005

• FxCop is intended for class library developers; however, anyone creating applications that should conform to .NET Framework best practices will benefit

• Can be customized to check for additional custom rules

Page 19: Coding Standards

Main References:

• .NET framework design guidelines by Microsoft @ http://msdn.microsoft.com/library/en-us/cpgenref/html/cpconnetframeworkdesignguidelines.asp

• McConnell, Steve. 2004. Code Complete. Microsoft Press

• http://www.dotnetspider.com/technology/tutorials/BestPractices.aspx

Page 20: Coding Standards

Bottom line:Use common sense and good

judgment

Page 21: Coding Standards

Thank you!Emad Magdy