• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 

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

on

  • 1,853 views

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

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.

Statistics

Views

Total Views
1,853
Views on SlideShare
1,838
Embed Views
15

Actions

Likes
0
Downloads
0
Comments
0

1 Embed 15

http://speakerrate.com 15

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

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

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