SlideShare una empresa de Scribd logo
1 de 38
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   } } ,[object Object]
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

Más contenido relacionado

La actualidad más candente

Introduction to automated quality assurance
Introduction to automated quality assuranceIntroduction to automated quality assurance
Introduction to automated quality assurance
Philip Johnson
 
findbugs Bernhard Merkle
findbugs Bernhard Merklefindbugs Bernhard Merkle
findbugs Bernhard Merkle
bmerkle
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with Findbugs
Carol McDonald
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworks
EndranNL
 

La actualidad más candente (20)

Working With Legacy Code
Working With Legacy CodeWorking With Legacy Code
Working With Legacy Code
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Introduction to automated quality assurance
Introduction to automated quality assuranceIntroduction to automated quality assurance
Introduction to automated quality assurance
 
findbugs Bernhard Merkle
findbugs Bernhard Merklefindbugs Bernhard Merkle
findbugs Bernhard Merkle
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with Findbugs
 
Working Effectively with Legacy Code
Working Effectively with Legacy CodeWorking Effectively with Legacy Code
Working Effectively with Legacy Code
 
TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black Hole
 
Working Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in PracticeWorking Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in Practice
 
Refactoring
RefactoringRefactoring
Refactoring
 
Working Effectively with Legacy Code
Working Effectively with Legacy CodeWorking Effectively with Legacy Code
Working Effectively with Legacy Code
 
JMockit
JMockitJMockit
JMockit
 
Refactoring - An Introduction
Refactoring - An IntroductionRefactoring - An Introduction
Refactoring - An Introduction
 
Write readable tests
Write readable testsWrite readable tests
Write readable tests
 
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
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworks
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
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
 
Journey's diary developing a framework using tdd
Journey's diary   developing a framework using tddJourney's diary   developing a framework using tdd
Journey's diary developing a framework using tdd
 

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

Commenting in Agile Development
Commenting in Agile DevelopmentCommenting in Agile Development
Commenting in Agile Development
Jan Rybák Benetka
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
frwebhelp
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
maheshm1206
 
Android Open source coading guidel ine
Android Open source coading guidel ineAndroid Open source coading guidel ine
Android Open source coading guidel ine
Pragati Singh
 

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

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
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
 
Commenting in Agile Development
Commenting in Agile DevelopmentCommenting in Agile Development
Commenting in Agile Development
 
Generics
GenericsGenerics
Generics
 
Ej Chpt#4 Final
Ej Chpt#4 FinalEj Chpt#4 Final
Ej Chpt#4 Final
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoC
 
Java Basics
Java BasicsJava Basics
Java Basics
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014
 
Best Coding Practices For Android Application Development
Best Coding Practices For Android Application DevelopmentBest Coding Practices For Android Application Development
Best Coding Practices For Android Application Development
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Annotation Processing
Annotation ProcessingAnnotation Processing
Annotation Processing
 
srgoc
srgocsrgoc
srgoc
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
 
The Naked Bundle - Tryout
The Naked Bundle - TryoutThe Naked Bundle - Tryout
The Naked Bundle - Tryout
 
J Unit
J UnitJ Unit
J Unit
 
Android Open source coading guidel ine
Android Open source coading guidel ineAndroid Open source coading guidel ine
Android Open source coading guidel ine
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup Belgium
 
Introduction
IntroductionIntroduction
Introduction
 

Más de David McCarter

Más de David McCarter (12)

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
 
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: 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)
 
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
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

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

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