SlideShare uma empresa Scribd logo
1 de 40
Back-2-Basics: .NET Coding Standards For The Real World
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
Win Free Software! Rules Provide your business card (or email and name)* Indicate on the back what software you are interested in Otherwise I will pick  Winners will be picked next week *Yes, most likely I’m going to send you and email about my user group (sddotnetdg.org) and or web site (dotNetTips.com) Prizes CodeRush and Refactor Pro from DevExpress (4) SecondCopy (automatic backup software) (5) * CodeIt.Right Standard from SubMain (4) *Requires mailing address and phone number
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.
Real World Analysis Example Scenario: In production Client Server Application with millions in sales Nine projects of 183,177 lines of .NET code written by multiple programmers (junior to principal) StyleCop Analyze Code.It Right 7,076 < 1,100 6,216 < 2,527 5,091 < 1,837 This is why you need to follow good coding practices throughout the lifecycle of the project!
Code.It Right Stats All Important
Assembly Layout
General Assembly Tips Never hardcode strings that might change based on deployment such as connection strings Best place to put them are in user or application level Settings in your application. Remember to save on exit and load on start! Automatic in VB.NET  Other locations can include: Registration Database, Databases and more…  DEMO
General Assembly Tips Sign (strong name) your assemblies, including the client applications.  Also, sign interop assemblies with the project’s .snk file Name assemblies in the following format: <Company>.<Component>.dll Project names should be named the same. Microsoft.VisualBasic.dll dotNetTips.Utility.dll Acme.Services.References.dll
Mark as CLS Compliant Forces your assembly to be compliant with the Common Language Specification (CLS).  Assemblies, modules, and types can be CLS-compliant even if some parts of the assembly, module, or type are not CLS-compliant, as long as these two conditions are met:  If the element is marked as CLS-compliant, the parts that are not CLS-compliant must be marked using CLSCompliantAttribute with its argument set to false.  A comparable CLS-compliant alternative member must be supplied for each member that is not CLS-compliant. DEMO
Element Order
Elements of the Same Type Should appear in this order: public elements protected elements internal elements private elements Use #region/ #endregion to group namespace-level and class-level elements Use separate regions to organize the private, protected, and internal members.
Namespaces The general rule for naming namespaces is to use the company name followed by the technology name and optionally the feature and design CompanyName.TechnologyName[.Feature][.Design]
Enums Use abbreviations sparingly for Enums and their values Do not use an Enum suffix on Enum type names Use a singular name for most Enum types, but use a plural name for Enum types that are bit fields
Enums Always add the FlagsAttribute to a bit field Enum type Avoid providing explicit values for Enums (unless necessary) Avoid specifying a type for an Enum Public Enum WebServiceAction   GetCurrentMode   PauseService   ResumeService   StartService   StopService End Enum
Interfaces Prefix interface names with the letter “I” Do not use the underscore character. Use abbreviations sparingly. Challenging to version over releases The smaller, more focused the interface the better public interface IDisposable {     // Methods
    void Dispose(); }
Classes Use a noun or noun phrase to name a class. Avoid putting multiple classes in a single file. A file name should reflect the class it contains.  Provide a default private constructor if there are only static methods and properties on a class.  Use Static Class in C# or a Module in VB.NET
Events Use Pascal case Use an EventHandler suffix on event handler names.  Name an event argument class with the EventArgs suffix. Use EventHandler<> to declare handlers. Be careful with non-UI threads calling back to the UI! Use the BackgroundWorker Control in Windows Forms DEMO
Member Variables (Fields) Use camel case as a rule, or uppercase for very small words Prefix private variables with a "_” Member variables should not be declared public Use a Property instead Const member variables may be declared public
Properties Use Pascal case Use a noun or noun phrase to name properties Properties that return arrays or collections should be methods.  Do not use write-only properties  Consider providing events that are raised when certain properties are changed.  Name them <Property>Changed
Properties Properties should not have dependencies on each other Setting one property should not affect other properties Properties should be settable in any order. DEMO
Constructors Do not call code from a constructor! Can cause Exceptions. Capture parameters only. Provide a constructor for every class.  Do not use the this./ Me. reference unless invoking another constructor from within a constructor. Provide a protected constructor that can be used by types in a derived class.
Destructors Avoid using destructors! It is not possible to predict when garbage collection will occur. The garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.  Implement IDisposible if you do! Use the try/finally (or Using) to make sure that unmanaged resources are disposed of even if an exception interrupts your application.  DEMO
Methods Use Pascal case Use verbs, verb phrases or verb-object pair to name methods Always mark public and protected methods as virtual/Overridable  in a non-sealed class.  Methods with return values should have a name describing the value returned DEMO
Method Overloading Use method overloading to provide different methods that do semantically the same thing.  Use method overloading instead of allowing default arguments.  Overloaded methods should call the most complete method If you provide the ability to override a method, make only the most complete overload virtual and define the other operations in terms of it DEMO
Do Not Expose Generic List List is a generic collection designed for performance not inheritance and Applies to public API’s Does not contain any virtual members Can not tell when updated Use Instead: System.Collections.ObjectModel.Collection System.Collections.ObjectModel.ReadOnlyCollection System.Collections.ObjectModel.KeyedCollection Use Interfaces: IDictionary DEMO
Stop Exceptions BEFORE They Happen! Defensive Programming
Prevent Exceptions 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 DEMO
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  DEMO
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! DEMO
TryParse Use the .TryParse method on value types when assigning from a string. WILL NOT cause an exception! Returns result of True/False DEMO
Exceptions When doing 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
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 Use camel case for local variables firstName
Accessing Class Member Variables Preface all calls to class members with this./Me., and place base./MyBase. before calls to all members of a base class Class BaseClass 	Public Sub ProcessData() 	End Sub End Class Class MainClass 	Inherits BaseClass 	Public Sub AnalyzeData() 	End Sub 	'Correct usage of this. and base. 	Public Sub Good() 		Me.AnalyzeData() 		MyBase.ProcessData() 	End Sub 	'Incorrect usage. 	Public Sub Bad() 		AnalyzeData() 		ProcessData() 	End Sub End Class
Strings When building a long string, always (almost) use StringBuilder, not string! C# StringBuilder builder = new StringBuilder("The error "); builder.Append(errorMessage); // errorMessage is defined elsewhere builder.Append("occurred at "); builder.Append(DateTime.Now); Console.WriteLine(builder.ToString()); VB Dim builder As New StringBuilder("The error ") builder.Append(errorMessage)  'errorMessage is defined elsewhere builder.Append("occurred at ") builder.Append(DateTime.Now) Console.WriteLine(builder.ToString()) DEMO

Mais conteúdo relacionado

Mais procurados

Entity framework code first
Entity framework code firstEntity framework code first
Entity framework code first
Confiz
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
Doncho Minkov
 
Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...
Shakir Majeed Khan
 

Mais procurados (20)

Getting started with entity framework
Getting started with entity framework Getting started with entity framework
Getting started with entity framework
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overview
 
Learn Entity Framework in a day with Code First, Model First and Database First
Learn Entity Framework in a day with Code First, Model First and Database FirstLearn Entity Framework in a day with Code First, Model First and Database First
Learn Entity Framework in a day with Code First, Model First and Database First
 
Ef code first
Ef code firstEf code first
Ef code first
 
Entity Framework v2 Best Practices
Entity Framework v2 Best PracticesEntity Framework v2 Best Practices
Entity Framework v2 Best Practices
 
ASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NETASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NET
 
Entity framework 4.0
Entity framework 4.0Entity framework 4.0
Entity framework 4.0
 
Ado.net
Ado.netAdo.net
Ado.net
 
Entity framework code first
Entity framework code firstEntity framework code first
Entity framework code first
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
 
Entity framework
Entity frameworkEntity framework
Entity framework
 
Introducing the Entity Framework
Introducing the Entity FrameworkIntroducing the Entity Framework
Introducing the Entity Framework
 
Ado .net
Ado .netAdo .net
Ado .net
 
LDAP Injection & Blind LDAP Injection in Web Applications
LDAP Injection & Blind LDAP Injection in Web ApplicationsLDAP Injection & Blind LDAP Injection in Web Applications
LDAP Injection & Blind LDAP Injection in Web Applications
 
Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...Sharepoint Saturday India Online best practice for developing share point sol...
Sharepoint Saturday India Online best practice for developing share point sol...
 
Dealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NETDealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NET
 
Oracle to vb 6.0 connectivity
Oracle to vb 6.0 connectivityOracle to vb 6.0 connectivity
Oracle to vb 6.0 connectivity
 
LDAP Injection & Blind LDAP Injection
LDAP Injection & Blind LDAP InjectionLDAP Injection & Blind LDAP Injection
LDAP Injection & Blind LDAP Injection
 
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)
 
ADO.NET Data Services &amp; Entity Framework
ADO.NET Data Services &amp; Entity FrameworkADO.NET Data Services &amp; Entity Framework
ADO.NET Data Services &amp; Entity Framework
 

Destaque (6)

Cultura paracas 6º prim
Cultura paracas 6º primCultura paracas 6º prim
Cultura paracas 6º prim
 
PRONOMBRES PERSONALES
PRONOMBRES PERSONALESPRONOMBRES PERSONALES
PRONOMBRES PERSONALES
 
Pronombre personal
Pronombre personalPronombre personal
Pronombre personal
 
LOS PRONOMBRES
LOS PRONOMBRESLOS PRONOMBRES
LOS PRONOMBRES
 
Presentación pronombres personales héctor
Presentación pronombres personales héctorPresentación pronombres personales héctor
Presentación pronombres personales héctor
 
PPT PRONOMBRES PERSONALES
PPT PRONOMBRES PERSONALESPPT PRONOMBRES PERSONALES
PPT PRONOMBRES PERSONALES
 

Semelhante a Back-2-Basics: .NET Coding Standards For The Real World

Best practices in enterprise applications
Best practices in enterprise applicationsBest practices in enterprise applications
Best practices in enterprise applications
Chandra Sekhar Saripaka
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
maheshm1206
 

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

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)
 
Bb Tequila Coding Style (Draft)
Bb Tequila Coding Style (Draft)Bb Tequila Coding Style (Draft)
Bb Tequila Coding Style (Draft)
 
Best practices in enterprise applications
Best practices in enterprise applicationsBest practices in enterprise applications
Best practices in enterprise applications
 
Generics
GenericsGenerics
Generics
 
Best Practices of Software Development
Best Practices of Software DevelopmentBest Practices of Software Development
Best Practices of Software Development
 
Code Quality Management iOS
Code Quality Management iOSCode Quality Management iOS
Code Quality Management iOS
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
 
Codings Standards
Codings StandardsCodings Standards
Codings Standards
 
Code Quality
Code QualityCode Quality
Code Quality
 
Code quality
Code qualityCode quality
Code quality
 
Android coding standard
Android coding standard Android coding standard
Android coding standard
 
Cs30 New
Cs30 NewCs30 New
Cs30 New
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
 
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
 
Code Metrics
Code MetricsCode Metrics
Code Metrics
 
Writing High Quality Code in C#
Writing High Quality Code in C#Writing High Quality Code in C#
Writing High Quality Code in C#
 
Automation tips
Automation tipsAutomation tips
Automation tips
 
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
 
Implementing DDD with C#
Implementing DDD with C#Implementing DDD with C#
Implementing DDD with C#
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questions
 

Mais de David McCarter

Mais de David McCarter (13)

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
 
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
 
Rock Your Code with Code Contracts
Rock Your Code with Code ContractsRock Your Code with Code Contracts
Rock Your Code with Code Contracts
 
.NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012).NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012)
 
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
 
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)
 
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
 
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

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)

Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
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
 
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...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

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

  • 1. Back-2-Basics: .NET Coding Standards For The Real World
  • 2.
  • 3. 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
  • 4. Win Free Software! Rules Provide your business card (or email and name)* Indicate on the back what software you are interested in Otherwise I will pick  Winners will be picked next week *Yes, most likely I’m going to send you and email about my user group (sddotnetdg.org) and or web site (dotNetTips.com) Prizes CodeRush and Refactor Pro from DevExpress (4) SecondCopy (automatic backup software) (5) * CodeIt.Right Standard from SubMain (4) *Requires mailing address and phone number
  • 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. Real World Analysis Example Scenario: In production Client Server Application with millions in sales Nine projects of 183,177 lines of .NET code written by multiple programmers (junior to principal) StyleCop Analyze Code.It Right 7,076 < 1,100 6,216 < 2,527 5,091 < 1,837 This is why you need to follow good coding practices throughout the lifecycle of the project!
  • 10. Code.It Right Stats All Important
  • 12. General Assembly Tips Never hardcode strings that might change based on deployment such as connection strings Best place to put them are in user or application level Settings in your application. Remember to save on exit and load on start! Automatic in VB.NET  Other locations can include: Registration Database, Databases and more… DEMO
  • 13. General Assembly Tips Sign (strong name) your assemblies, including the client applications. Also, sign interop assemblies with the project’s .snk file Name assemblies in the following format: <Company>.<Component>.dll Project names should be named the same. Microsoft.VisualBasic.dll dotNetTips.Utility.dll Acme.Services.References.dll
  • 14. Mark as CLS Compliant Forces your assembly to be compliant with the Common Language Specification (CLS). Assemblies, modules, and types can be CLS-compliant even if some parts of the assembly, module, or type are not CLS-compliant, as long as these two conditions are met: If the element is marked as CLS-compliant, the parts that are not CLS-compliant must be marked using CLSCompliantAttribute with its argument set to false. A comparable CLS-compliant alternative member must be supplied for each member that is not CLS-compliant. DEMO
  • 16. Elements of the Same Type Should appear in this order: public elements protected elements internal elements private elements Use #region/ #endregion to group namespace-level and class-level elements Use separate regions to organize the private, protected, and internal members.
  • 17. Namespaces The general rule for naming namespaces is to use the company name followed by the technology name and optionally the feature and design CompanyName.TechnologyName[.Feature][.Design]
  • 18. Enums Use abbreviations sparingly for Enums and their values Do not use an Enum suffix on Enum type names Use a singular name for most Enum types, but use a plural name for Enum types that are bit fields
  • 19. Enums Always add the FlagsAttribute to a bit field Enum type Avoid providing explicit values for Enums (unless necessary) Avoid specifying a type for an Enum Public Enum WebServiceAction GetCurrentMode PauseService ResumeService StartService StopService End Enum
  • 20. Interfaces Prefix interface names with the letter “I” Do not use the underscore character. Use abbreviations sparingly. Challenging to version over releases The smaller, more focused the interface the better public interface IDisposable { // Methods void Dispose(); }
  • 21. Classes Use a noun or noun phrase to name a class. Avoid putting multiple classes in a single file. A file name should reflect the class it contains. Provide a default private constructor if there are only static methods and properties on a class. Use Static Class in C# or a Module in VB.NET
  • 22. Events Use Pascal case Use an EventHandler suffix on event handler names. Name an event argument class with the EventArgs suffix. Use EventHandler<> to declare handlers. Be careful with non-UI threads calling back to the UI! Use the BackgroundWorker Control in Windows Forms DEMO
  • 23. Member Variables (Fields) Use camel case as a rule, or uppercase for very small words Prefix private variables with a "_” Member variables should not be declared public Use a Property instead Const member variables may be declared public
  • 24. Properties Use Pascal case Use a noun or noun phrase to name properties Properties that return arrays or collections should be methods. Do not use write-only properties Consider providing events that are raised when certain properties are changed. Name them <Property>Changed
  • 25. Properties Properties should not have dependencies on each other Setting one property should not affect other properties Properties should be settable in any order. DEMO
  • 26. Constructors Do not call code from a constructor! Can cause Exceptions. Capture parameters only. Provide a constructor for every class. Do not use the this./ Me. reference unless invoking another constructor from within a constructor. Provide a protected constructor that can be used by types in a derived class.
  • 27. Destructors Avoid using destructors! It is not possible to predict when garbage collection will occur. The garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams. Implement IDisposible if you do! Use the try/finally (or Using) to make sure that unmanaged resources are disposed of even if an exception interrupts your application. DEMO
  • 28. Methods Use Pascal case Use verbs, verb phrases or verb-object pair to name methods Always mark public and protected methods as virtual/Overridable in a non-sealed class. Methods with return values should have a name describing the value returned DEMO
  • 29. Method Overloading Use method overloading to provide different methods that do semantically the same thing. Use method overloading instead of allowing default arguments. Overloaded methods should call the most complete method If you provide the ability to override a method, make only the most complete overload virtual and define the other operations in terms of it DEMO
  • 30. Do Not Expose Generic List List is a generic collection designed for performance not inheritance and Applies to public API’s Does not contain any virtual members Can not tell when updated Use Instead: System.Collections.ObjectModel.Collection System.Collections.ObjectModel.ReadOnlyCollection System.Collections.ObjectModel.KeyedCollection Use Interfaces: IDictionary DEMO
  • 31. Stop Exceptions BEFORE They Happen! Defensive Programming
  • 32. Prevent Exceptions 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 DEMO
  • 33. 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 DEMO
  • 34. 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! DEMO
  • 35. TryParse Use the .TryParse method on value types when assigning from a string. WILL NOT cause an exception! Returns result of True/False DEMO
  • 36. Exceptions When doing 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
  • 38. 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 Use camel case for local variables firstName
  • 39. Accessing Class Member Variables Preface all calls to class members with this./Me., and place base./MyBase. before calls to all members of a base class Class BaseClass Public Sub ProcessData() End Sub End Class Class MainClass Inherits BaseClass Public Sub AnalyzeData() End Sub 'Correct usage of this. and base. Public Sub Good() Me.AnalyzeData() MyBase.ProcessData() End Sub 'Incorrect usage. Public Sub Bad() AnalyzeData() ProcessData() End Sub End Class
  • 40. Strings When building a long string, always (almost) use StringBuilder, not string! C# StringBuilder builder = new StringBuilder("The error "); builder.Append(errorMessage); // errorMessage is defined elsewhere builder.Append("occurred at "); builder.Append(DateTime.Now); Console.WriteLine(builder.ToString()); VB Dim builder As New StringBuilder("The error ") builder.Append(errorMessage) 'errorMessage is defined elsewhere builder.Append("occurred at ") builder.Append(DateTime.Now) Console.WriteLine(builder.ToString()) DEMO
  • 41. Parameters Use descriptive parameter names Parameter names should be descriptive enough such that the name of the parameter and its value can be used to determine its meaning in most scenarios Do not prefix parameter names with Hungarian type notation Public Function ManageIIs(ByVal server As String, ByVal userName As String, ByVal password As System.Security.SecureString, ByVal domain As String, ByVal instance As String, ByVal action As IIsWebServiceAction) As Int32 End Function
  • 42. Generic Type Parameters If possible use descriptive type parameters for generic parameters Prefix with T Use only T, K etc if is self-explanatory C# public static string ConvertArrayToString<TArray>(TArray[] array) where TArray : IEnumerable { } VB Public Shared Function ConvertArrayToString(Of TArray As {IEnumerable})(ByVal array As TArray()) As String End Function DEMO
  • 43. 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!
  • 44. 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 DEMO
  • 45. Let’s See What We Have Learned/ Know What’s Wrong With This Code?
  • 46. Constructor public class FileCache { public FileCache(string tempPath)   {    var appData = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),Global.UserDataFolder); var cacheDir = Path.Combine(appData, tempPath);    if (Directory.Exists(cacheDir) == false) {      Directory.CreateDirectory(cacheDir);   }    } } public class FileCache { public FileCache(string tempPath)   {    this.TempPath = tempPath;   } } 46
  • 47. Method public static string SQLValue(string parameter, string value) {   if (String.IsNullOrEmpty(parameter))   {   throw new ArgumentNullException("parameter");   }     if (string.IsNullOrEmpty(value))     return (parameter + " = NULL");   else     return (parameter + " = '" + value.Trim() + "'"); } public static string SQLValue(string parameter, string value) { if (String.IsNullOrEmpty(parameter))    {      throw new ArgumentNullException("parameter");     }     if (string.IsNullOrEmpty(value))    return (String.Format("{0} = NULL", parameter));   else     return (String.Format("{0} = '{1}'", parameter, value.Trim())); } public static string CreateSQLParameter(string name, string value) { if (String.IsNullOrEmpty(name))   {    throw new ArgumentNullException(”name");   }     return string.IsNullOrEmpty(value) ? (String.Format("{0} = NULL", name)) : (String.Format("{0} = '{1}'", name, value.Trim())); } public static string SQLValue(string name, string value) { if (string.IsNullOrEmpty(value))    return (name + " = NULL");   else    return (name + " = '" + value.Trim() + "'"); }
  • 48. Exception private void UpdateVendor() { try { //Code that causes and exception } catch (ValidationException ex) { //Clean up code throw ex; } catch (Exception ex) { LogWriter.WriteException(ex, System.Diagnostics.TraceEventType.Error, this.Name); } }
  • 49. Structure Public Structure UserInfo Private _contactName As String Public Property ContactName() As String Get Return _contactName End Get Set(ByVal value As String) _contactName = value End Set End Property Private _email As String Public Property Email() As String Get Return _email End Get Set(ByVal value As String) _email = value End Set End Property Public Overrides Function ToString() As String Return Me.ContactName End Function Public Overloads Overrides Function GetHashCode() As Integer Return Me.ContactName.GetHashCode Or Me.Email.GetHashCode End Function Public Overloads Overrides Function Equals(ByVal obj As [Object]) As Boolean Dim testObject As UserInfo = CType(obj, UserInfo) If Me.ContactName = testObject.ContactName AndAlso Me.Email = testObject.Email Return True Else Return False End If End Function End Structure Public Structure UserInfo Private _contactName As String Public Property ContactName() As String Get Return _contactName End Get Set(ByVal value As String) _contactName = value End Set End Property Private _email As String Public Property Email() As String Get Return _email End Get Set(ByVal value As String) _email = value End Set End Property Public Overrides Function ToString() As String Return Me.ContactName End Function Public Overloads Overrides Function GetHashCode() As Integer Return Me.ContactName.GetHashCode Or Me.Email.GetHashCode End Function End Structure Public Structure UserInfo Private _contactName As String Public Property ContactName() As String Get Return _contactName End Get Set(ByVal value As String) _contactName = value End Set End Property Private _email As String Public Property Email() As String Get Return _email End Get Set(ByVal value As String) _email = value End Set End Property Public Overrides Function ToString() As String Return Me.ContactName End Function End Structure Public Structure UserInfo Private _contactName As String Public Property ContactName() As String Get Return _contactName End Get Set(ByVal value As String) _contactName = value End Set End Property Private _email As String Public Property Email() As String Get Return _email End Get Set(ByVal value As String) _email = value End Set End Property End Structure
  • 50. Enum public enum MergeTypes { InsCo = 1, Agents = 2, Vendors = 3 } public enum MergeType { InsuranceCompanies, Agents, Vendors } public enum MergeType { None, InsuranceCompanies, Agents, Vendors }
  • 51. Fields public class Contact { protected string mNamePrefix = ""; protected string mFirstName = ""; protected string mLastName = ""; protected string mPhone1 = ""; protected string mExtension1 = ""; protected string mEmailAddress = ""; //Code } public class Contact { private string _namePrefix = string.Empty; protected string NamePrefix { get { return _namePrefix; } set { _namePrefix = value; } } //Code }
  • 52. Events public delegate void ReportListEventHandler(object sender, ReportListEventArgs e); public event ReportListEventHandler ReportSelected; public event EventHandler<ReportListEventArgs> ReportSelected;
  • 54. 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! 54
  • 55. Resourses (Besides My Book) Design Guidelines for Class Library Developers http://DGForClassLibrary.notlong.com .NET Framework General Reference Naming Guidelines http://namingguide.notlong.com

Notas do Editor

  1. C# Use Style Cope to enforce.
  2. DEMO: DefensiveProgramming.vb - SafeIntegerSet
  3. The original exception object should not be re-throwed explicitly. Violation of this rule will complicate debugging and ruin the exception&apos;s stack trace.
  4. ToStringGetHashCodeEquals
  5. Or use an automatic property!