Your SlideShare is downloading. ×
0
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

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

1,577

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 …

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,577
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Back-2-Basics: .NET Coding Standards For The Real World
  • 2.
  • 3. 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!
  • 4. 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
  • 5. Agenda
    5
  • 6. Overview
  • 7. 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!!!
  • 8. 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.
  • 9. 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!
  • 10. Issues I see all the time!
    Common Coding Mistakes
  • 11. 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).
  • 12. 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
  • 13. 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.
  • 14. 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!
    • 15. Can cause Exceptions.
    • 16. Capture parameters only.
    14
  • 17. 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)
  • 18. 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.
  • 19. 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.
  • 20. 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.
  • 21. 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.
  • 22. 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.
  • 23. 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!
  • 24. 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.
  • 25. 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
  • 26. 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
  • 27. Stop Exceptions BEFORE They Happen!
    Defensive Programming
  • 28. 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!
  • 29. All Data Is Bad…
    Until Verified!
  • 30. 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
  • 31. 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!
  • 32. 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
  • 33. Code Style
  • 34. 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!
  • 35. 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
  • 36.
  • 37. Summary
  • 38. 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
  • 39. Resourses (Besides My Book)
    Design Guidelines for Class Library Developers
    http://DGForClassLibrary.notlong.com
    .NET Framework General Reference Naming Guidelines
    http://namingguide.notlong.com

×