Back-2-Basics: .NET Coding Standards For The Real World<br />
dotNetDave Conference DVD!<br />Packed full of:<br />Videos of all sessions from 2010 & 2011(1)!<br />Slide decks from 201...
Check Out Your Local User Groups!<br />San Diego Cloud Computing User Group<br />www.azureusergroup.com/group/sandiegoazur...
Agenda<br />5<br />
Overview<br />
Why Do You Need Standards?<br />First, you might not agree witheverything I say… that’s okay!<br />Pick a standard for you...
After Selecting a Standard<br />Make sure it’s easily available to each programmer<br />Print or electronically<br />Enfor...
Violations<br />Real World Analysis Example<br />Scenario: In production Client Server Application with millions in sales<...
Issues I see all the time!<br />Common Coding Mistakes	<br />
Assembly<br />[assembly: AssemblyTitle(“My App")]<br />[assembly: AssemblyDescription(“My App Management System")]<br />[a...
Type Design<br />public struct MaxLength{    public int CustomerId;    public int PolicyNumber;}<br />public struct MaxLen...
Static Classes<br />public class AssemblyHelper<br />{<br />public static IEnumerable<Type> FindDerivedTypes(string path,<...
Constructor<br />public class FileCache<br />{<br />  public FileCache(string tempPath)<br />  {<br />    var cacheDir= En...
Can cause Exceptions.
Capture parameters only.</li></ul>14<br />
Enums<br />public enum ADODB_PersistFormatEnumEnum<br />{<br />adPersistXML = 1,<br />adPersistADTG = 0<br />}<br />public...
Enums<br />public enum AutoSizeSettings <br />{<br />    flexAutoSizeColWidth,<br />flexAutoSizeRowHeight<br />}<br />publ...
Collections<br />public class ModelItemCollection : Collection<ModelItem> <br />{<br />    //Code Removed for brevity.<br ...
Fields<br />public class Response<br />{<br />    protected WebResponse response;<br />}<br />public class Response<br />{...
Properties<br />public string[] Cookies { get; private set; }<br />public string[] LoadCookies()<br />{<br />	//Code<br />...
IDisposable<br />public void Dispose() <br />{<br />    Close();<br />}<br />public void Dispose() <br />{<br />    Close(...
Performance<br />if (txtPassword.Text == "")<br />{<br />   MessageBox.Show("Enter Password.");<br />}<br />if (String.IsN...
Performance<br />private bool _showAdvancedSettings = false;<br />private bool _showAdvancedSettings;<br />Value types ini...
Exceptions<br />private byte[] GetContents(string location)<br />{<br />    try<br />{<br />    return ContentManager.Arch...
Globalization<br />var postDate = Convert.ToDateTime(“1/1/2010”);<br />var postDate = Convert.ToDateTime(“1/1/2010”, <br /...
Stop Exceptions BEFORE They Happen!<br />Defensive Programming<br />
Prevent Exceptions/ Issues<br />Practice Defensive Programming!<br />Any code that might cause an exception (accessing fil...
All Data Is Bad…<br />Until Verified!<br />
Parameters<br />Always check for valid parameter arguments<br />Perform argument validation for every public or protected ...
Enums<br />Never assume that Enum arguments will be in the defined range.<br />Enums are just an Int32, so any valid numbe...
Exceptions<br />When performing any operation that could cause an exception, wrap in Try - Catch block<br />Use System.Env...
Code Style<br />
Commenting<br />Comment your code!<br />While coding or before<br />Keep it short and understandable<br />Mark changes wit...
Xml Commenting<br />Now supported by VB.NET and C#!<br />Comment all public classes and methods!<br />XML can be turned in...
Summary<br />
Products To Help Out<br />StyleCop<br />http://stylecop.notlong.com<br />CodeIt.Right<br />http://codeitright.notlong.com<...
Upcoming SlideShare
Loading in …5
×

Back-2-Basics: .NET Coding Standards For The Real World (2011)

1,673
-1

Published on

Revamped for 2011 (90% new material), 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
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,673
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Back-2-Basics: .NET Coding Standards For The Real World (2011)

  1. 1. Back-2-Basics: .NET Coding Standards For The Real World<br />
  2. 2.
  3. 3. dotNetDave Conference DVD!<br />Packed full of:<br />Videos of all sessions from 2010 & 2011(1)!<br />Slide decks from 2011 & 2010!<br />Demo projects from 2011 & 2010!<br />David McCarter’s .NETinterview Questions!<br />Extras<br />Conference Photos from 2010!<br />Surprise videos!<br />Book + DVD $25!<br />Only $15!<br />
  4. 4. Check Out Your Local User Groups!<br />San Diego Cloud Computing User Group<br />www.azureusergroup.com/group/sandiegoazureusergroup<br />San Diego .NET Developers Group<br />www.sddotnetdg.org<br />San Diego .NET User Group<br />www.sandiegodotnet.com<br />San Diego SQL Server User Group<br />www.sdsqlug.org<br />
  5. 5. Agenda<br />5<br />
  6. 6. Overview<br />
  7. 7. Why Do You Need Standards?<br />First, you might not agree witheverything I say… that’s okay!<br />Pick a standard for your company<br />Every programmer on the same page<br />Easier to read and understand code<br />Easier to maintain code<br />Produces more stable, reliable code<br />Stick to the standard!!!<br />
  8. 8. After Selecting a Standard<br />Make sure it’s easily available to each programmer<br />Print or electronically<br />Enforce via code reviews<br />Provide programs to make it easier for programmers to maintain:<br />StyleCop – Free for C# programmers.<br />CodeIt.Right – Enterprise edition shares profiles. Can create custom profiles for your company.<br />
  9. 9. Violations<br />Real World Analysis Example<br />Scenario: In production Client Server Application with millions in sales<br />23 projects of 755,600 lines of .NET code<br />StyleCop<br />fxcop<br />Code.It Right<br />13,152<br />32,798<br />32,696<br />This is why you need to follow good coding practices throughout the lifecycle of the project!<br />
  10. 10. Issues I see all the time!<br />Common Coding Mistakes <br />
  11. 11. Assembly<br />[assembly: AssemblyTitle(“My App")]<br />[assembly: AssemblyDescription(“My App Management System")]<br />[assembly: AssemblyCompany(“Acme International")]<br />[assembly: AssemblyProduct(“My App")]<br />[assembly: AssemblyCopyright("Copyright © 2011 Acme Inc.")]<br />[assembly: ComVisible(false)]<br />[assembly: AssemblyVersion("2010.3.0.20")]<br />[assembly: AssemblyFileVersion("2010.3.0.20")]<br />[assembly: CLSCompliant(true)]<br />[assembly: AssemblyTitle(“My App")]<br />[assembly: AssemblyDescription(“My App Management System")]<br />[assembly: AssemblyCompany(“Acme International")]<br />[assembly: AssemblyProduct(“My App")]<br />[assembly: AssemblyCopyright("Copyright © 2011 Acme Inc.")]<br />[assembly: ComVisible(false)]<br />[assembly: AssemblyVersion("2010.3.0.20")]<br />[assembly: AssemblyFileVersion("2010.3.0.20")]<br />Does not use the System.CLSCompliantAttribute<br />Ensures that all its types and members are compliant with the Common Language Specification (CLS). <br />
  12. 12. Type Design<br />public struct MaxLength{ public int CustomerId;    public int PolicyNumber;}<br />public struct MaxLength{ public int CustomerId;    public int PolicyNumber;<br /> public override bool Equals(object obj)<br />{<br />var e = (MaxLength)obj;<br />return e.CustomerId == this.CustomerId && <br />e.PolicyNumber == this.PolicyNumber;<br />}}<br />Equals for value types uses Reflection<br />Computationally expensive.<br />Override Equals to gain increased performance<br />
  13. 13. Static Classes<br />public class AssemblyHelper<br />{<br />public static IEnumerable<Type> FindDerivedTypes(string path,<br /> string baseType, <br /> bool classOnly)<br />{<br /> //Code removed for brevity<br /> }<br />}<br />public static class AssemblyHelper<br />{<br />public static IEnumerable<Type> FindDerivedTypes(string path,<br /> string baseType, <br /> bool classOnly)<br />{<br /> //Code removed for brevity<br /> }<br />}<br />Classes with only static members should be marked sealed (NotInheritable for Visual Basic) .<br />Cannot be overridden in a derived type or inherited.<br />Performs slightly better because all its properties and methods are implicitly sealed and the compiler can often inline them.<br />
  14. 14. Constructor<br />public class FileCache<br />{<br /> public FileCache(string tempPath)<br />  {<br />   var cacheDir= Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);<br />    if (Directory.Exists(cacheDir) == false)<br /> { <br />     Directory.CreateDirectory(cacheDir);<br />  }<br />   }<br />}<br />public class FileCache<br />{<br /> string _tempPath;<br /> public FileCache(string tempPath)<br />  {<br /> _tempPath= tempPath<br /> }<br />}<br /><ul><li>Do not call code from a constructor!
  15. 15. Can cause Exceptions.
  16. 16. Capture parameters only.</li></ul>14<br />
  17. 17. Enums<br />public enum ADODB_PersistFormatEnumEnum<br />{<br />adPersistXML = 1,<br />adPersistADTG = 0<br />}<br />public enum DatabasePersistFormat<br />{<br /> Xml,<br /> Adtg<br />}<br />Do not use an Enum suffix on Enum type names<br />Do not specify number unless the Enum is a bit flag or absolutely necessary (stored in file, database)<br />
  18. 18. Enums<br />public enum AutoSizeSettings <br />{<br /> flexAutoSizeColWidth,<br />flexAutoSizeRowHeight<br />}<br />public enum AutoSizeSetting <br />{<br /> ColumnWidth,<br /> RowHeight<br />}<br />Use a singular name for most Enum types, but use a plural name for Enum types that are bit fields<br />Enum and elements should be Pascal case.<br />
  19. 19. Collections<br />public class ModelItemCollection : Collection<ModelItem> <br />{<br /> //Code Removed for brevity.<br />}<br />public class ModelList : Collection<ModelItem> <br />{<br /> //Code Removed for brevity.<br />}<br />When deriving from a collection base type, use the base type in the type name.<br />
  20. 20. Fields<br />public class Response<br />{<br /> protected WebResponse response;<br />}<br />public class Response<br />{<br /> protected WebResponse CurrentResponse {get; set;}<br />}<br />Public instance fields should never be defined. <br />Use private fields wrapped inside public properties should be used instead. <br />This allows validation the incoming value.<br />This allows events to be thrown.<br />
  21. 21. Properties<br />public string[] Cookies { get; private set; }<br />public string[] LoadCookies()<br />{<br /> //Code<br />}<br />Return a copy of the array, to keep the array tamper-proof, because of arrays returned by properties are not write-protected. <br />Affects performance negatively. <br />Method should be used when returning array. <br />
  22. 22. IDisposable<br />public void Dispose() <br />{<br /> Close();<br />}<br />public void Dispose() <br />{<br /> Close();<br /> GC.SuppressFinalize();<br />}<br />Once the Dispose method has been called, it is typically unnecessary for the garbage collector to call the disposed object's finalizer method. <br />To prevent automatic finalization, Dispose implementations should call the GC.SuppressFinalize method. <br />
  23. 23. Performance<br />if (txtPassword.Text == "")<br />{<br /> MessageBox.Show("Enter Password.");<br />}<br />if (String.IsNullOrEmpty(txtPassword.Text))<br />{<br /> MessageBox.Show("Enter Password.");<br />}<br />Length property of a string should be compared with zero.<br />Use IsNullOrEmpty(System.String) method!<br />
  24. 24. Performance<br />private bool _showAdvancedSettings = false;<br />private bool _showAdvancedSettings;<br />Value types initialized with its default value<br />Increase the size of an assembly<br />Degrade performance. <br />CLR (Common Language Runtime) initializes all fields with their default values. <br />
  25. 25. Exceptions<br />private byte[] GetContents(string location)<br />{<br /> try<br />{<br /> return ContentManager.Archiver.GetArchive(location);<br /> }<br />catch (Exception ex)<br /> {<br /> LogWriter.WriteException(ex, TraceEventType.Error,);<br />return null;<br />}<br />}<br />private byte[] GetContents(string location)<br />{<br /> return ContentManager.Archiver.GetArchive(location);<br />}<br />Do not catch general Exception or SystemException. Only specific exception should be caught. <br />If caught re-throw in the catch block.<br />“API” assemblies should not log exceptions/ events<br />
  26. 26. Globalization<br />var postDate = Convert.ToDateTime(“1/1/2010”);<br />var postDate = Convert.ToDateTime(“1/1/2010”, <br /> CultureInfo.InvariantCulture);<br />Culture-specific information should be explicitly specified if it is possible.<br />Call appropriate overload of a method and pass<br />System.Globalization.CultureInfo.CurrentCulture<br />System.Globalization.CultureInfo.InvariantCulture<br />
  27. 27. Stop Exceptions BEFORE They Happen!<br />Defensive Programming<br />
  28. 28. Prevent Exceptions/ Issues<br />Practice Defensive Programming!<br />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<br />For example, call File.Exists to avoid a FileNotFoundException<br />Check and object for null<br />Check a DataSet for rows<br />Check an Array for bounds<br />Check String for null or empty<br />Cleaning up unused objects!<br />
  29. 29. All Data Is Bad…<br />Until Verified!<br />
  30. 30. Parameters<br />Always check for valid parameter arguments<br />Perform argument validation for every public or protected method<br />Throw meaningful exceptions to the developer for invalid parameter arguments<br />Use the System.ArgumentException class<br />Or your own class derived from System.ArgumentException <br />
  31. 31. Enums<br />Never assume that Enum arguments will be in the defined range.<br />Enums are just an Int32, so any valid number in that range could be sent in!<br />Always use Enum.IsDefined to verify value before using!<br />
  32. 32. Exceptions<br />When performing any operation that could cause an exception, wrap in Try - Catch block<br />Use System.Environment.FailFast instead if unsafe for further execution<br />Do not catch non-specific exceptions (for common API’s)<br />Use Finally for cleanup code<br />When throwing Exceptions try using from System instead of creating custom Exceptions<br />Use MyApplication_UnhandledException event in VB.NET WinForm apps<br />Use Application_Error event in ASP.NET apps<br />
  33. 33. Code Style<br />
  34. 34. Commenting<br />Comment your code!<br />While coding or before<br />Keep it short and understandable<br />Mark changes with explanation, who changed it and the date (if that is your company standard)<br />NEVER WAIT UNTIL AFTER YOU ARE DONE CODING!<br />
  35. 35. Xml Commenting<br />Now supported by VB.NET and C#!<br />Comment all public classes and methods!<br />XML can be turned into help docs, help html with applications like Sandcastle<br />http://sandcastle.notlong.com<br />Very useful for teams and documentation for users.<br />Make this easy by using GhostDoc<br />http://ghostdoc.notlong.com<br />
  36. 36.
  37. 37. Summary<br />
  38. 38. Products To Help Out<br />StyleCop<br />http://stylecop.notlong.com<br />CodeIt.Right<br />http://codeitright.notlong.com<br />FXCop<br />http://fxcop.notlong.com<br />Or Use Analyze in VS Team Systems<br />Refactor Pro! For Visual Studio<br />http://refactorpro.notlong.com <br />I Use All 4!<br />36<br />
  39. 39. Resourses (Besides My Book)<br />Design Guidelines for Class Library Developers<br />http://DGForClassLibrary.notlong.com<br />.NET Framework General Reference Naming Guidelines<br />http://namingguide.notlong.com<br />

×