Your SlideShare is downloading. ×
Rock Your .NET Coding Standards - 2013
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Introducing the official SlideShare app

Stunning, full-screen experience for iPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Rock Your .NET Coding Standards - 2013

981
views

Published on

With lots of 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 common coding …

With lots of 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 common coding mistakes, 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 on 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
981
On Slideshare
0
From Embeds
0
Number of Embeds
1
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
  • 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'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.
  • Transcript

    • 1. David McCarter dotnetdave@live.com
    • 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 @realdotnetdave davidmccarter dotnetdave@live.com
    • 3. Conference DVD’s • Rock Your Code DVD • Videos of sessions • Sides, sample code • More! • Rock Your Technical Interview DVD • Full length video of session • Expert Videos • Engineer Videos • Interview Questions • Slide deck • More!
    • 4. OVERVIEW COMMON CODING MISTAKES DEFENSIVE PROGRAMMING CODING STYLE SUMMARY
    • 5.   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!
    • 6.  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". If standards are not 100% applicable, only break on purpose
    • 7.  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!
    • 8.  In production consumer application    10K customers, growing to 100K by the end of the year 3 Assemblies (server-side) FXCop Violations   2,870! This is why you need to follow good coding practices throughout the lifecycle of the project!
    • 9.  Turn on Code Analysis!   Always do this when creating a new project! Choose appropriate rule set.
    • 10.    Its origins cannot be verified. It cannot be loaded into the GAC. The common language runtime cannot warn users if the contents of the assembly have been altered.
    • 11.  Use the System.CLSCompliantAttribute   Ensures that all its types and members are compliant with the Common Language Specification (CLS). Fill out all Assembly attributes [assembly: [assembly: [assembly: [assembly: [assembly: [assembly: [assembly: [assembly: [assembly: AssemblyTitle(“My App")] AssemblyDescription(“My App Management System")] AssemblyCompany(“Acme International")] AssemblyProduct(“My App")] AssemblyCopyright("Copyright © 2011 Acme Inc.")] ComVisible(false)] AssemblyVersion("2010.3.0.20")] AssemblyFileVersion("2010.3.0.20")] CLSCompliant(true)]
    • 12.    Default value for Enum (int) is zero Use None or most commonly used member for most Enum’s Use None for an Enum that uses FlagsAttribute public enum { Off Error Warning Info Verbose } TraceLevel = = = = = 0, 1, 2, 3, 4
    • 13.  Do not catch general Exception or SystemException (DLL’s).    Only specific exception should be caught. If caught, re-throw in the catch block. “API” assemblies should not log exceptions/ events private byte[] GetContents(string location) { try { return ContentManager.Archiver.GetArchive(location); } catch (FileNotFoundException ex) { //Clean Up code… throw; } }
    • 14.  List<T> is designed for performance not inheritance.   List<T> does not contain virtual members that make it easier to implement new behaviors. Use instead IEnumerable, Collection<T>, ReadOnlyCollection<T> or KeyedCollection<Tkey, Titem> from ObjectModel public IEnumerable<FileInformation> DirectoryFilesInformation(string directory) { List<FileInformation> result = new List<FileInformation>(); //Code removed that loads data return new result.AsEnumerable(); }
    • 15.  Event handler methods take two parameters:    System.Object named 'sender’ System.EventArgs named 'e'. Use EventHandler<T> public class CounterChangedEventArgs : System.EventArgs { public CounterChangedEventArgs(){} public int32 NewValue { get { return this._newValue; } set { this._newValue = value; } } } public event EventHandler<CounterChangedEventArgs> ValueChanged;
    • 16.  Rethink properties named:   Uri, urn, Urn, url or Url A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities Uri _someUri; public Uri SomeUri { get { return _someUri; } set { _someUri = value; } }
    • 17.  Use preferred terms for properties that have been obsoleted:       LogIn  LogOn LogOut  LogOff SignOn  SignIn SignOff  SignOut Writeable  Writable Cancelled  Canceled
    • 18.   Property names should not match get methods Get methods and properties should have names that clearly distinguish their function. protected string DatabaseConnectionString { get { (ManagerSettings.DatabaseConnectionString); } } protected string GetDatabaseConnectionString (DCDatabaseTypes typeIn) { … }
    • 19. public class FileCache public class FileCache { { public FileCache(string tempPath) {string _tempPath; var cacheDir= Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); public FileCache(string tempPath) {if (Directory.Exists(cacheDir) == false) { _tempPath = tempPath; Directory.CreateDirectory(cacheDir); }} } } }   Do not call code from a constructor  Can cause Exceptions! Capture required parameters only  Otherwise use object initializers
    • 20.  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. public class Response { public WebResponse response; }
    • 21.   Length property of a string should be compared with zero. Use IsNullOrEmpty(System.String) method! ifif (txtPassword.Text == "") (String.IsNullOrEmpty(txtPassword.Text)) { { MessageBox.Show("Enter Password.");"); MessageBox.Show("Enter Password. } }
    • 22.  Do not initialize Value types with its default value     Increase the size of an assembly Degrade performance Adds to maintenance costs. CLR (Common Language Runtime) initializes all fields with their default values. _verified; private bool _verified = false;
    • 23.  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); MemoryStream msnew new MemoryStream(); using (var ms = = MemoryStream()) logoImage.Save(ms, ImageFormat.Jpeg); { logoImage.Save(ms, ImageFormat.Jpeg); ms.Close(); } }
    • 24.      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! Always code for reusability! Keep generics in mind. Real World Example:  There was a method that was over 3,500 lines of code! About 3495 lines were in the If portion and 3 in the Else portion!
    • 25.  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!
    • 26.   Exceptions dramatically effects performance of your application Unhandled Exceptions can cause your application to die a horrible death.     Will piss off your customer! Will piss off our boss! Can corrupt data ALWAYS log exceptions!  Check out my logging system on CodePlex  Writing new version, looking for ideas like Azure support
    • 27.  Any code that might cause an exception (accessing files, using objects like DataSets etc.) should check the object/ value (depending on the type) so an Exception is not thrown       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!
    • 28.    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   Makes checking parameters MUCH easier! See my video on YouTube
    • 29. 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 }
    • 30.   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; } }
    • 31.  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 the framework instead of creating custom Exceptions Use CurrentDomain_UnhandledException/ MyApplication_UnhandledException event in WinForm apps Use Application_Error event in ASP.NET apps
    • 32.   Use consistent naming across variables Avoid single character variable names   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.   i, t etc. ArgumentException or FileStream DO NOT vary variables by case! (C#)
    • 33.  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. Very hard to change once in production! Be consistent! Use Regions appropriately to make your code more readable  Don’t use in methods!
    • 34.  Comment your code!    While coding or before // Dear maintainer: Keep it short and understandable // // Once you are done trying to do not match the code Change/ remove comments that 'optimize' this routine, (after // and have realized what a terrible mistake modificationincrement the following counter as that was, of the code) // please a warning   // Mark changes with explanation, who changed it and the date and // total_hours_wasted_here = 42 time   This includes removing TODO comments // to the next guy: Include software change #, bug # etc. If you use proper naming standards you can comment less!
    • 35. if (x.a && b.z == 1 || c.f) { //Perform work } var userHasPermissions = x.a && b.z == 1 || c.f; if(userHasPermissions) { //Perform work }
    • 36.   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://submain.com
    • 37. Summary
    • 38.   One Type per file 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 use unit testing!
    • 39. Check Code for Problems Style Cop Code.It Right FXCop Check in Code to TFS
    • 40.  Refactor Pro! For Visual Studio   DevExpress StyleCop   Microsoft Templates:    CodeIt.Right   http://vstemplates.codeplex.com/ http://vssnippets.codeplex.com/ Submain VS Analyze or FXCop  Visual Studio/ Microsoft
    • 41.   Design Guidelines for Class Library Developers .NET Framework General Reference Naming Guidelines
    • 42. Questions? All Pictures © David McCarter •Presentation Downloads •slideshare.com/dotnetdave •Please Rate My Session: •speakerrate.com/dotnetdave •David McCarter’s •.NET Coding Standards •dotnettips.com •Geek Swag •geekstuff.notlong.com @realdotnetdave davidmccarter dotnetdave@live.com