SlideShare uma empresa 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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante a 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
 

Semelhante 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
 

Mais 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
 

Mais 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

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
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 RobisonAnna Loughnan Colquhoun
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 

Último (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 

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