Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

.NET Coding Standards For The Real World (2012)


Published on

Revamped for 2012, this session will guide any level of programmer to greater productivity by providing the information needed to write consistent, maintainable code. Learn about project setup, assembly layout, code style, defensive programming and much, much more. Code tips are included to help you write better, error free applications. Lots of code examples in C# and VB.NET. This session is based off my latest book, David McCarter's .NET Coding Standards.

Published in: Technology
  • Dating for everyone is here: ❶❶❶ ❶❶❶
    Are you sure you want to  Yes  No
    Your message goes here
  • Sex in your area is here: ♥♥♥ ♥♥♥
    Are you sure you want to  Yes  No
    Your message goes here

.NET Coding Standards For The Real World (2012)

  1. 1. Please SetPhones To David McCarterVibrate © David McCarter 2012
  2. 2. About David McCarter•Microsoft MVP•David McCarter’s .NET Coding Standards •• •700+ Tips, Tricks, Articles, Links!•Open Source Projects: ••San Diego .NET Developers Group ••UCSD Classes • @davidmccarter davidmccarter dmccarter © David McCarter 2012
  3. 3.  Packed full of:  Videos of all sessions from last 2 years!  Slide decks from last 2 years!  Demo projects from last two years!  David McCarter’s .NET interview Questions! Extras  Conference Photos!  Surprise videos! Order online:  © David McCarter 2012
  4. 4. Overview Common Coding Mistakes Defensive Programming Coding Style Summary5 © David McCarter 2012
  5. 5. © David McCarter 2012
  6. 6.  First, you might not agree with everything I say… that’s okay! Pick a standard for your company  Every programmer on the same page  Easier to read and understand code  Easier to maintain code  Produces more stable, reliable code Stick to the standard!!! Important part of Agile! © David McCarter 2012
  7. 7.  Make sure it’s easily available to each programmer  Print or online (Share Point) Enforce via code reviews, pair programming If the standard is insufficient or is causing problems the standard can be adjusted, but it should not be "hacked". © David McCarter 2012
  8. 8.  Provide programs to make it easier for programmers to maintain:  StyleCop – FREE from Microsoft for C# programmers.  CodeIt.Right – Enterprise edition shares profiles. Can create custom profiles for your company.   FxCop (Analyze in VS) – FREE from Microsoft  Use Refactoring Tools! © David McCarter 2012
  9. 9.  Scenario: In production Client Server Application with millions in sales  23 projects of 755,600 lines of .NET code*Violations This is why you need to follow good coding practices throughout the lifecycle of the project! © David McCarter 2012
  10. 10. © David McCarter 2012
  11. 11. [assembly: AssemblyTitle(“My App")] [assembly: AssemblyDescription(“My App Management System")] [assembly: AssemblyCompany(“Acme International")] [assembly: AssemblyProduct(“My App")] [assembly: AssemblyCopyright("Copyright © 2011 Acme Inc.")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("2010.3.0.20")] [assembly: AssemblyFileVersion("2010.3.0.20")] [assembly: CLSCompliant(true)] Use the System.CLSCompliantAttribute  Ensures that all its types and members are compliant with the Common Language Specification (CLS). Fill out all Assembly attributes © David McCarter 2012
  12. 12.  Turn on Code Analysis!  Always do this when creating a new project!  Choose appropriate rule set. © David McCarter 2012
  13. 13. public class FileCache { string _tempPath; public FileCache(string tempPath) public FileCache(string tempPath) { { var cacheDir= Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); _tempPath = tempPath; } if (Directory.Exists(cacheDir) == false) } { Directory.CreateDirectory(cacheDir); } } }  Do not call code from a constructor!  Can cause Exceptions.  Capture parameters only.14 © David McCarter 2012
  14. 14. public class Response { protected WebResponse response; CurrentResponse {get; set;} } Public instance fields should never be used.  Use private fields wrapped inside public properties should always be used instead. This allows validation the incoming value. This allows events to be thrown. © David McCarter 2012
  15. 15. if (String.IsNullOrEmpty(txtPassword.Text)) (txtPassword.Text == "") { MessageBox.Show("Enter Password. "); Password."); } Length property of a string should be compared with zero. Use IsNullOrEmpty(System.String) method! © David McCarter 2012
  16. 16. private bool _showAdvancedSettings = false; _showAdvancedSettings; Do not initialize Value types with its default value  Increase the size of an assembly  Degrade performance. CLR (Common Language Runtime) initializes all fields with their default values. © David McCarter 2012
  17. 17. private byte[] GetContents(string location) { try { return ContentManager.Archiver.GetArchive(location); } catch (FileNotFoundException ex) (Exception ex) { //Clean Up code LogWriter.WriteException(ex, TraceEventType.Error,); throw; return null; } } Do not catch general Exception or SystemException. Only specific exception should be caught. If caught, re-throw in the catch block. “API” assemblies should not log exceptions/ events © David McCarter 2012
  18. 18.  Always use the using/ Using statement to make sure that unmanaged resources are disposed of even if an exception interrupts your application. using (var logoImage = new Bitmap(_logoPath)) { Bitmap logoImage = new Bitmap(_logoPath); using (var ms = new MemoryStream()) MemoryStream ms = new MemoryStream(); { logoImage.Save(ms, ImageFormat.Jpeg); logoImage.Save(ms, ImageFormat.Jpeg); ms.Close(); } } © David McCarter 2012
  19. 19.  Refactor for code reuse, low cyclomatic complexity values. If you can’t see your code on one screen in the editor, then it’s probably too long! Keep generics in mind. Real World Example:  There was a method that was ~3500 lines of code! About 3495 lines were in the If portion and 3 in the Else portion! © David McCarter 2012
  20. 20.  There are two kinds of programmers:  Complexifiers are averse to reduction.  Simplifiers thrive on concision. If your method, class etc. seems huge or overly complicated, then you are most likely doing it wrong!  Refactor!  Ask a follow programmer!  Pair programming!  Code review! © David McCarter 2012
  21. 21. © David McCarter 2012
  22. 22.  Practice Defensive Programming!  Any code that might cause an exception (accessing files, using objects like DataSets etc.) should check the object (depending on the type) so an Exception is not thrown  For example, call File.Exists to avoid a FileNotFoundException  Check an object for null  Check a DataSet for rows  Check an Array for bounds  Check String for null or empty  Clean up unused objects! © David McCarter 2012
  23. 23. © David McCarter 2012
  24. 24.  Always check for valid parameter arguments Perform argument validation for every public or protected method Throw meaningful exceptions to the developer for invalid parameter arguments  Use the System.ArgumentException class  Or your own class derived from System.ArgumentException Use Code Contracts in .NET 4  See my video on YouTube © David McCarter 2012
  25. 25. public IEnumerable<Type> FindDerivedTypes(string path, string baseType, bool classOnly){ if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path", "Must pass in path and file name."); } if (string.IsNullOrEmpty(baseType)) { throw new ArgumentNullException("baseType", "Parent Type must be defined"); } if (File.Exists(path) == false) { throw new FileNotFoundException("Could not find assembly file.", path); } //Code removed for brevity} © David McCarter 2012
  26. 26.  Never assume that Enum arguments will be in the defined range. Always use Enum.IsDefined to verify value before using! public Environment.SpecialFolder RootFolder { get { return this._rootFolder; } set { if (!Enum.IsDefined(typeof(Environment.SpecialFolder), value)) { throw new InvalidEnumArgumentException("value", (int)value, typeof(Environment.SpecialFolder)); } this._rootFolder = value; } } © David McCarter 2012
  27. 27.  When performing any operation that could cause an exception, wrap in Try - Catch block  Do not catch non-specific exceptions (for common API’s)  Use Finally for cleanup code  When throwing Exceptions try using from System instead of creating custom Exceptions  Use MyApplication_UnhandledException event in VB.NET WinForm apps  Use Application_Error event in ASP.NET apps © David McCarter 2012
  28. 28. © David McCarter 2012
  29. 29.  Use consistent naming across variables Avoid single character variable names  i, t etc. Do not abbreviate variable words (such as num, instead of number)  Unless they are well known like Xml, Html or IO If deriving from a core type, add the suffix of the identify type.  ArgumentException or FileStream DO NOT vary variables by case! (C#) © David McCarter 2012
  30. 30.  Take time to name your classes, methods, namespaces and parameters so that they are easy to understand  Use consistent naming across methods, assemblies, any project artifact  Don’t use parameters names like sql, sql2 etc. Be consistent! © David McCarter 2012
  31. 31.  Comment your code!  While coding or before  Keep it short and understandable  Change/ remove comments that do not match the code (after modification of the code)  This includes removing TODO comments  Mark changes with explanation, who changed it and the date and time  Include software change #, bug # etc. © David McCarter 2012
  32. 32.  Examples of bad comments:  “I was here 10/2/1960” “This change made at the request of Satan” “Dont know why this call is here doesnt seem to do anything” “This code doesnt work... so Ive commented it out and left it here for eternity...” NEVER WAIT UNTIL AFTER YOU ARE DONE CODING! © David McCarter 2012
  33. 33. //If user has permissionsif (x.a && b.z == 1 || c.f){ //Perform work}var userHasPermissions = x.a && b.z == 1 || c.f;if(userHasPermissions){ //Perform work} © David McCarter 2012
  34. 34.  Comment all public classes and methods! XML can be turned into help docs, help html with applications like Sandcastle  Very useful for teams and documentation for users. Make this easy by using GhostDoc  © David McCarter 2012
  35. 35. © David McCarter 2012
  36. 36. © David McCarter 2012
  37. 37.  One Type per file Don’t hold Synchronization lock longer than absolutely necessary (multi-threading) Always code for globalization!  Resource files  Formatting value types (dates, integer etc.)! Be consistent with { and } bracketing in C# Only use var/Dim when it’s obvious from the right side of the statement what the type is Always using unit testing! © David McCarter 2012
  38. 38. Check Code for Problems Code.ItStyle Cop FXCop Right Check in Code to TFS © David McCarter 2012
  39. 39.  Refactor Pro! For Visual Studio  1. StyleCop  2. CodeIt.Right  3. VS Analyze or FXCop  http://fxcop.notlong.com40 © David McCarter 2012
  40. 40.  Design Guidelines for Class Library Developers  .NET Framework General Reference Naming Guidelines  © David McCarter 2012
  41. 41. Questions?•Presentation Downloads ••Please Rate My Session: ••David McCarter’s .NET CodingStandards ••Geek Swag • @davidmccarter davidmccarter dmccarter © David McCarter 2012