SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

Working With Legacy Code
Working With Legacy CodeWorking With Legacy Code
Working With Legacy CodeAndrea Polci
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
Introduction to automated quality assurance
Introduction to automated quality assuranceIntroduction to automated quality assurance
Introduction to automated quality assurancePhilip Johnson
 
findbugs Bernhard Merkle
findbugs Bernhard Merklefindbugs Bernhard Merkle
findbugs Bernhard Merklebmerkle
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with FindbugsCarol McDonald
 
Working Effectively with Legacy Code
Working Effectively with Legacy CodeWorking Effectively with Legacy Code
Working Effectively with Legacy Codeslicklash
 
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 HoleNoam Kfir
 
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 PracticeAmar Shah
 
Refactoring - An Introduction
Refactoring - An IntroductionRefactoring - An Introduction
Refactoring - An IntroductionGiorgio Vespucci
 
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 WorldDavid McCarter
 
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 frameworksEndranNL
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework OverviewMario Peshev
 
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 TestSeb Rose
 
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 tddeduardomg23
 

Tendances (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
 

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

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 WorldDavid McCarter
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java DevelopersYakov Fain
 
Commenting in Agile Development
Commenting in Agile DevelopmentCommenting in Agile Development
Commenting in Agile DevelopmentJan Rybák Benetka
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developementfrwebhelp
 
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 2014Matthias Noback
 
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 DevelopmentKetan Raval
 
Annotation Processing
Annotation ProcessingAnnotation Processing
Annotation ProcessingJintin Lin
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for javamaheshm1206
 
The Naked Bundle - Tryout
The Naked Bundle - TryoutThe Naked Bundle - Tryout
The Naked Bundle - TryoutMatthias Noback
 
Android Open source coading guidel ine
Android Open source coading guidel ineAndroid Open source coading guidel ine
Android Open source coading guidel inePragati Singh
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumMatthias Noback
 
Introduction
IntroductionIntroduction
Introductionrichsoden
 

Similaire à 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
 

Plus de David McCarter

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 - V3David McCarter
 
How To Survive The Technical Interview
How To Survive The Technical InterviewHow To Survive The Technical Interview
How To Survive The Technical InterviewDavid McCarter
 
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 ServicesDavid McCarter
 
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 ServicesDavid McCarter
 
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 & ExtensionsDavid McCarter
 
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 .NETDavid McCarter
 
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)David McCarter
 
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)David McCarter
 
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 .NETDavid McCarter
 
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)David McCarter
 
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)David McCarter
 
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 2010David McCarter
 

Plus 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
 

Dernier

So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 

Dernier (20)

So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 

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