SlideShare a Scribd company logo
Please Set
Phones To
                                      David McCarter
Vibrate




                                     dotnettips.dotnetdave@gmail.com

             © David McCarter 2012
About David McCarter
•Microsoft MVP
•David McCarter’s .NET Coding Standards
    •http://codingstandards.notlong.com/
•dotNetTips.com
    •700+ Tips, Tricks, Articles, Links!
•Open Source Projects:
    •http://codeplex.com/dotNetTips
•San Diego .NET Developers Group
    •www.sddotnetdg.org
•UCSD Classes
    •http://dotnetdaveclasses.notlong.com

     @davidmccarter

     davidmccarter
     dmccarter
                                               dotnettips.dotnetdave@gmail.com

                       © David McCarter 2012
   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:
       http://dotnettips.wordpress.com/store/


                        © David McCarter 2012
Overview

     Common Coding Mistakes

      Defensive Programming

     Coding Style

    Summary

5         © David McCarter 2012
© David McCarter 2012
   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
   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
   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.
           submain.com/products/codeit.right.aspx
       FxCop (Analyze in VS) – FREE from Microsoft
       Use Refactoring Tools!

                     © David McCarter 2012
   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
© David McCarter 2012
[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
   Turn on Code Analysis!
       Always do this when creating a new project!
       Choose appropriate rule set.
                  © David McCarter 2012
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
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
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
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
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
   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
   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
   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
© David McCarter 2012
   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
© David McCarter 2012
   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
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
    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
   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
© David McCarter 2012
   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
   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
   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
   Examples of bad comments:
       “I was here 10/2/1960”
        “This change made at the request of Satan”
        “Don't know why this call is here doesn't seem
        to do anything”
        “This code doesn't work... so I've commented it
        out and left it here for eternity...”
   NEVER WAIT UNTIL AFTER YOU ARE
    DONE CODING!


                  © David McCarter 2012
//If user has permissions
if (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
   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



                  © David McCarter 2012
© David McCarter 2012
© David McCarter 2012
   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
Check Code for Problems
                    Code.It
Style Cop                       FXCop
                     Right




    Check in Code to TFS

        © David McCarter 2012
    Refactor Pro! For Visual Studio
             http://refactorpro.notlong.com
     1.   StyleCop
             http://stylecop.notlong.com
     2.   CodeIt.Right
             http://codeitright.notlong.com
     3.   VS Analyze or FXCop
             http://fxcop.notlong.com



40                       © David McCarter 2012
   Design Guidelines for Class Library
    Developers
       http://DGForClassLibrary.notlong.com
   .NET Framework General Reference
    Naming Guidelines
       http://namingguide.notlong.com




                  © David McCarter 2012
Questions?
•Presentation Downloads
    •slideshare.com/dotnetdave
•Please Rate My Session:
    •speakerrate.com/dotnetdave
•David McCarter’s .NET Coding
Standards
    •codingstandards.notlong.com
•Geek Swag
    •geekstuff.notlong.com

    @davidmccarter

    davidmccarter
    dmccarter
                                             dotnettips.dotnetdave@gmail.com

                     © David McCarter 2012

More Related Content

What's hot

Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principles
Edorian
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
maheshm1206
 

What's hot (20)

Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principles
 
Clean code & design patterns
Clean code & design patternsClean code & design patterns
Clean code & design patterns
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
[教材] 例外處理設計與重構實作班201309
[教材] 例外處理設計與重構實作班201309[教材] 例外處理設計與重構實作班201309
[教材] 例外處理設計與重構實作班201309
 
Java & J2EE Coding Conventions
Java & J2EE Coding ConventionsJava & J2EE Coding Conventions
Java & J2EE Coding Conventions
 
How To Become A Good C# Programmer
How To Become A Good C# ProgrammerHow To Become A Good C# Programmer
How To Become A Good C# Programmer
 
Rock Your Code With Code Contracts -2013
Rock Your Code With Code Contracts -2013Rock Your Code With Code Contracts -2013
Rock Your Code With Code Contracts -2013
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
 
Coding standard and coding guideline
Coding standard and coding guidelineCoding standard and coding guideline
Coding standard and coding guideline
 
Commenting Best Practices
Commenting Best PracticesCommenting Best Practices
Commenting Best Practices
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summary
 
Clean code
Clean codeClean code
Clean code
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
 
Clean code
Clean codeClean code
Clean code
 
Why Your Test Suite Sucks - PHPCon PL 2015
Why Your Test Suite Sucks - PHPCon PL 2015Why Your Test Suite Sucks - PHPCon PL 2015
Why Your Test Suite Sucks - PHPCon PL 2015
 
C#, .NET, Java - General Naming and Coding Conventions
C#, .NET, Java - General Naming and Coding ConventionsC#, .NET, Java - General Naming and Coding Conventions
C#, .NET, Java - General Naming and Coding Conventions
 
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampClean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
 
Clean code
Clean codeClean code
Clean code
 
Java 例外處理壞味道與重構技術
Java 例外處理壞味道與重構技術Java 例外處理壞味道與重構技術
Java 例外處理壞味道與重構技術
 

Similar to .NET Coding Standards For The Real World (2012)

Use Eclipse technologies to build a modern embedded IDE
Use Eclipse technologies to build a modern embedded IDEUse Eclipse technologies to build a modern embedded IDE
Use Eclipse technologies to build a modern embedded IDE
Benjamin Cabé
 

Similar to .NET Coding Standards For The Real World (2012) (20)

Getting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafGetting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with Thymeleaf
 
Rules SDK IBM WW BPM Forum March 2013
Rules SDK IBM WW BPM Forum March 2013Rules SDK IBM WW BPM Forum March 2013
Rules SDK IBM WW BPM Forum March 2013
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
 
Introduction to YouDebug - Scriptable Java Debugger
Introduction to YouDebug - Scriptable Java DebuggerIntroduction to YouDebug - Scriptable Java Debugger
Introduction to YouDebug - Scriptable Java Debugger
 
Deep Dive Modern Apps Lifecycle with Visual Studio 2012: How to create cross ...
Deep Dive Modern Apps Lifecycle with Visual Studio 2012: How to create cross ...Deep Dive Modern Apps Lifecycle with Visual Studio 2012: How to create cross ...
Deep Dive Modern Apps Lifecycle with Visual Studio 2012: How to create cross ...
 
JavaOne 2017 CON2902 - Java Code Inspection and Testing Power Tools
JavaOne 2017 CON2902 - Java Code Inspection and Testing Power ToolsJavaOne 2017 CON2902 - Java Code Inspection and Testing Power Tools
JavaOne 2017 CON2902 - Java Code Inspection and Testing Power Tools
 
Coding Naked 2023
Coding Naked 2023Coding Naked 2023
Coding Naked 2023
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App Engine
 
Testing your application on Google App Engine
Testing your application on Google App EngineTesting your application on Google App Engine
Testing your application on Google App Engine
 
Unit Testing Documentum Foundation Classes Code
Unit Testing Documentum Foundation Classes CodeUnit Testing Documentum Foundation Classes Code
Unit Testing Documentum Foundation Classes Code
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Use Eclipse technologies to build a modern embedded IDE
Use Eclipse technologies to build a modern embedded IDEUse Eclipse technologies to build a modern embedded IDE
Use Eclipse technologies to build a modern embedded IDE
 
Unit Testing DFC
Unit Testing DFCUnit Testing DFC
Unit Testing DFC
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Divide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsDivide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.js
 
Open Source ERP Technologies for Java Developers
Open Source ERP Technologies for Java DevelopersOpen Source ERP Technologies for Java Developers
Open Source ERP Technologies for Java Developers
 
New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)
 

More from David McCarter

More from David McCarter (15)

Röck Yoür Technical Interview - V3
Röck Yoür Technical Interview - V3Röck Yoür Technical Interview - V3
Röck Yoür Technical Interview - V3
 
Back-2-Basics: Code Contracts
Back-2-Basics: Code ContractsBack-2-Basics: Code Contracts
Back-2-Basics: Code Contracts
 
How To Survive The Technical Interview
How To Survive The Technical InterviewHow To Survive The Technical Interview
How To Survive The Technical Interview
 
Real World API Design Using The Entity Framework Services
Real World API Design Using The Entity Framework ServicesReal World API Design Using The Entity Framework Services
Real World API Design Using The Entity Framework Services
 
Building nTier Applications with Entity Framework Services
Building nTier Applications with Entity Framework ServicesBuilding nTier Applications with Entity Framework Services
Building nTier Applications with Entity Framework Services
 
Code Easier With Visual Studio 2010 & Extensions
Code Easier With Visual Studio 2010 & ExtensionsCode Easier With Visual Studio 2010 & Extensions
Code Easier With Visual Studio 2010 & Extensions
 
Back-2-Basics: Exception & Event Instrumentation in .NET
Back-2-Basics: Exception & Event Instrumentation in .NETBack-2-Basics: Exception & Event Instrumentation in .NET
Back-2-Basics: Exception & Event Instrumentation in .NET
 
Building nTier Applications with Entity Framework Services (Part 2)
Building nTier Applications with Entity Framework Services (Part 2)Building nTier Applications with Entity Framework Services (Part 2)
Building nTier Applications with Entity Framework Services (Part 2)
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Back-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldBack-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real World
 
Back-2-Basics: Exception & Event Instrumentation in .NET
Back-2-Basics: Exception & Event Instrumentation in .NETBack-2-Basics: Exception & Event Instrumentation in .NET
Back-2-Basics: Exception & Event Instrumentation in .NET
 
Back-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldBack-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real World
 
Building nTier Applications with Entity Framework Services (Part 2)
Building nTier Applications with Entity Framework Services (Part 2)Building nTier Applications with Entity Framework Services (Part 2)
Building nTier Applications with Entity Framework Services (Part 2)
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Building N Tier Applications With Entity Framework Services 2010
Building N Tier Applications With Entity Framework Services 2010Building N Tier Applications With Entity Framework Services 2010
Building N Tier Applications With Entity Framework Services 2010
 

Recently uploaded

Recently uploaded (20)

Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 

.NET Coding Standards For The Real World (2012)

  • 1. Please Set Phones To David McCarter Vibrate dotnettips.dotnetdave@gmail.com © David McCarter 2012
  • 2. About David McCarter •Microsoft MVP •David McCarter’s .NET Coding Standards •http://codingstandards.notlong.com/ •dotNetTips.com •700+ Tips, Tricks, Articles, Links! •Open Source Projects: •http://codeplex.com/dotNetTips •San Diego .NET Developers Group •www.sddotnetdg.org •UCSD Classes •http://dotnetdaveclasses.notlong.com @davidmccarter davidmccarter dmccarter dotnettips.dotnetdave@gmail.com © David McCarter 2012
  • 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:  http://dotnettips.wordpress.com/store/ © David McCarter 2012
  • 4. Overview Common Coding Mistakes Defensive Programming Coding Style Summary 5 © David McCarter 2012
  • 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. 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. 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.  submain.com/products/codeit.right.aspx  FxCop (Analyze in VS) – FREE from Microsoft  Use Refactoring Tools! © David McCarter 2012
  • 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
  • 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. Turn on Code Analysis!  Always do this when creating a new project!  Choose appropriate rule set. © David McCarter 2012
  • 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. 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. 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. 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. 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. 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. 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. 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
  • 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
  • 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. 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. 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. 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
  • 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. 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. 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. Examples of bad comments:  “I was here 10/2/1960” “This change made at the request of Satan” “Don't know why this call is here doesn't seem to do anything” “This code doesn't work... so I've commented it out and left it here for eternity...”  NEVER WAIT UNTIL AFTER YOU ARE DONE CODING! © David McCarter 2012
  • 33. //If user has permissions if (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. 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 © David McCarter 2012
  • 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. Check Code for Problems Code.It Style Cop FXCop Right Check in Code to TFS © David McCarter 2012
  • 39. Refactor Pro! For Visual Studio  http://refactorpro.notlong.com 1. StyleCop  http://stylecop.notlong.com 2. CodeIt.Right  http://codeitright.notlong.com 3. VS Analyze or FXCop  http://fxcop.notlong.com 40 © David McCarter 2012
  • 40. Design Guidelines for Class Library Developers  http://DGForClassLibrary.notlong.com  .NET Framework General Reference Naming Guidelines  http://namingguide.notlong.com © David McCarter 2012
  • 41. Questions? •Presentation Downloads •slideshare.com/dotnetdave •Please Rate My Session: •speakerrate.com/dotnetdave •David McCarter’s .NET Coding Standards •codingstandards.notlong.com •Geek Swag •geekstuff.notlong.com @davidmccarter davidmccarter dmccarter dotnettips.dotnetdave@gmail.com © David McCarter 2012

Editor's Notes

  1. Cyclomatic complexity (or conditional complexity) is a software metric (measurement). It was developed by Thomas J. McCabe, Sr. in 1976 and is used to indicate the complexity of a program. It directly measures the number of linearly independent paths through a program&apos;s source code. The concept, although not the method, is somewhat similar to that of general text complexity measured by the Flesch-Kincaid Readability Test.