1 / 21

Coding Standards

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

naomi
Télécharger la présentation

Coding Standards

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Coding Standards

  2. 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);

  3. Naming variables

  4. Naming methods t1 = calc1(); t2 = calc2(); S2 = calcAll(t1, t2); netPrice = CalculatePrice(); tax = CalculateTax(); sum = CalculateSum(netPrice, tax);

  5. 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 total to = to + li(i); } total = 0.0 for (int line = 0 ; lines <linesTotal ; line++) { total = total + LineValue(line); }

  6. “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.

  7. “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; }

  8. 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. 

  9. 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,..

  10. 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 case The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized. For example: backColor

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

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

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

  14. 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 }

  15. 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 ); } }

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

  17. 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);

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

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

  20. Bottom line:Use common sense and good judgment

  21. Thank you!Emad Magdy

More Related