SlideShare a Scribd company logo
.NET Coding Best Practices DIGICorp
Need for this seminar We all just write code for “working application” Any developer can do that Need to write “Efficient Code” Try to achieve excellence for yourself if not for your company Try to become the ' M ost  V alued  P rofessional' of your company Writing 'Efficient Code' is an art and you must learn and practice it.
Naming Conventions and Standards Pascal Casing - First character of all words are Upper Case and other characters are lower case.  Camel Casing - First character of all words,  except the first word  are Upper Case and other characters are lower case.
Use Pascal casing for Class names public class  H ello W orld  {  ...  }
Use Pascal casing for Method names   public class HelloWorld  {  void  S ay H ello(string name)  {  ...  }  }
Use Camel casing for variables and method parameters   public class HelloWorld  {  int  t otal C ount = 0;  void SayHello(string  n ame)  {  string  f ull M essage = "Hello " + name;  ...  }  }
Do not use Hungarian notation to name variables In earlier days most of the programmers liked it - having the data type as a prefix for the variable name and using  m_  as prefix for member variables.  Example:  string m_sName;  int nAge;  However, in .NET coding standards, this is not reccommended. Usage of datatype and  M_  to represent member variables should not be used. All variables should use camel casing.
Use Meaningful, descriptive words to name variables   Do not use abbreviations. Use  name, address, salary  etc instead of  nam, addr, sal   Do not use single character variable names like  i, n, x  etc. Use names like  index, temp   One exception in this case would be variables used for iterations in loops  for ( int i = 0; i < count; i++ )  {  ...  }  Do not use underscores (_) in variable names.  Namespace names should follow the standard pattern  <company name>.<product name>.<top level module>.<bottom level module>
File name should match with class name   For example, for the class HelloWorld, the file name should be helloworld.cs (or, helloworld.vb)
Indentation and Spacing Use TAB for indentation. Do not use SPACES.  Comments should be in the same level as the code.  Curly braces ( {} ) should be in the same level as the code outside the braces.  Use one blank line to separate logical groups of code.
Which code looks better? bool SayHello (string name) {  string fullMessage = &quot;Hello &quot; + name;  DateTime currentTime = DateTime.Now;  string message = fullMessage + &quot;, the time is : &quot; + currentTime.ToShortTimeString();  MessageBox.Show ( message );  if ( ... )  {  // Do something //  ...  return false;  }  return true;  }  bool SayHello (string name) {  string fullMessage = &quot;Hello &quot; + name;  DateTime currentTime = DateTime.Now;  string message = fullMessage + &quot;, the time is : &quot; + currentTime.ToShortTimeString();  MessageBox.Show ( message );  if ( ... )  {  // Do something //  ...  return false;  }  return true;  }
Indentation and Spacing There should be one and only one single blank line between each method inside the class.  The curly braces should be on a separate line and not in the same line as if, for etc.  Good: if ( ... )  {   // Do something  }  Not good: if ( ... )  {   // Do something  }
Indentation and Spacing Use a single space before and after each operator and brackets  Good:   if ( showResult == true )  {  for ( int i = 0; i < 10; i++ )  {  //  }  }  Not Good:   if(showResult==true)  {  for(int i= 0;i<10;i++)  {  //  }  }
Follow the best practices for best programming Avoid having too large files. If a file has more than 300~400 lines of code, you must consider refactoring code into helper classes.  Avoid writing very long methods. A method should typically have 1~25 lines of code. If a method has more than 25 lines of code, you must consider re factoring into separate methods.
Naming Methods Method name should tell what it does. Do not use misleading names. If the method name is obvious, there is no need of documentation explaining what the method does.  Good:  void Save PhoneNumber  ( string phoneNumber)  {  // Save the phone number.  }  Not Good:   // This method will save the phone number.  void SaveData ( string phoneNumber )  {  // Save the phone number. }
One job per Method A method should do only 'one job'. Do not combine more than one job in a single method, even if those jobs are very small  Good:  // Save the address.  SaveAddress ( address );  // Send an email to the supervisor to inform that the address is updated.  SendEmail ( address, email );  void SaveAddress ( string address )  {  // Save the address. //  ...  }  void SendEmail ( string address, string email )  {  // Send an email to inform the supervisor that the address is changed. //  ...  }
One job per Method Not Good:  // Save address and send an email to the supervisor to inform that the address is updated.  SaveAddress ( address, email );  void SaveAddress ( string address, string email )  {  // Job 1.  // Save the address.  // ...  // Job 2.  // Send an email to inform the supervisor that the address is changed.  // ...  }
Types Use the c# or VB.NET specific types, rather than the alias types defined in System namespace. Good:  int age;  string name;  object contactInfo;  Not Good:  Int16 age;  String name;  Object contactInfo;
Do not hardcode numbers. Use constants instead.  Do not hardcode strings. Use resource files.  Avoid using many member variables. Declare local variables and pass it to methods instead of sharing a member variable between methods. If you share a member variable between methods, it will be difficult to track which method changed the value and when.
Use of ENUM Use enum wherever required. Do not use numbers or strings to indicate discrete values. Good:   enum MailType  {  Html,  PlainText,  Attachment  }  void SendMail (string message, MailType mailType)  {  switch ( mailType )  {  case MailType.Html:  // Do something  break;  case MailType.PlainText:  // Do something  break;  case MailType.Attachment:  // Do something  break;  default:  // Do something  break;  }  }
Use of ENUM Not Good:  void SendMail (string message, MailType mailType)  {  switch ( mailType )  {  case “Html”:  // Do something  break;  case “PlainText”:  // Do something  break;  case “Attachment”:  // Do something  break;  default:  // Do something  break;  }  }
Do not make the member variables public or protected. Keep them private and expose public/protected  Properties .  Never hardcode a path or drive name in code. Get the application path programmatically and use relative path.  Never assume that your code will run from drive &quot;C:&quot;. You may never know, some users may run it from network or from a &quot;Z:&quot;.  In the application start up, do some kind of &quot;self check&quot; and ensure all required files and dependencies are available in the expected locations. Check for database connection in start up, if required. Give a friendly message to the user in case of any problems.  If the required configuration file is not found, application should be able to create one with default values.  If a wrong value found in the configuration file, application should throw an error or give a message and also should tell the user what are the correct values.
Error Messages Error messages should help the user to solve the problem. Never give error messages like &quot;Error in Application&quot;, &quot;There is an error&quot; etc. Instead give specific messages like &quot;Failed to update database. Please make sure the login id and password are correct.&quot;  When displaying error messages, in addition to telling what is wrong, the message should also tell what should the user do to solve the problem. Instead of message like &quot;Failed to update database.&quot;, suggest what should the user do: &quot;Failed to update database. Please make sure the login id and password are correct.&quot;  Show short and friendly message to the user. But log the actual error with all possible information. This will help a lot in diagnosing problems.
Comments Do not write comments for every line of code and every variable declared. Write comments  wherever required . But good readable code will  require  very less comments. If all variables and method names are meaningful, that would make the code very readable and will not need much comments.  Less lines of comments will make the code more elegant. But if the code is not clean/readable and there are less comments, that is worse.  If you have to use some complex or weird logic for any reason, document it very well with sufficient comments.  If you initialize a numeric variable to a special number other than 0, -1 etc, document the reason for choosing that value.  The bottom line is, write clean, readable code such a way that it doesn't need any comments to understand.  Do a spell check on comments and also make sure proper grammar and punctuation is used.
Exception Handling Never do a 'catch exception and do nothing'. If you hide an exception, you will never know if the exception happened or not.  In case of exceptions, give a friendly message to the user, but log the actual error with all possible details about the error, including the time it occurred, method and class name etc.  Always catch only the specific exception, not generic exception.
Good Exception Handling Good:   void ReadFromFile ( string fileName )  {  try  {  // read from file.  }  catch (FileIOException ex)  {  // log error.  // re-throw exception depending on your case.  throw;  }  }
Bad Exception Handling Not Good:   void ReadFromFile ( string fileName )  {  try  {  // read from file.  }  catch (Exception ex)  {  // Catching general exception is bad... we will never know whether it  // was a file error or some other error.  // Here you are hiding an exception.  // In this case no one will ever know that an exception happened.  return &quot;&quot;;  }  }
Exception Handling No need to catch the general exception in all your methods. Leave it open and let the application crash. This will help you find most of the errors during development cycle.  You can have an application level (thread level) error handler where you can handle all general exceptions. In case of an 'unexpected general error', this error handler should catch the exception and should log the error in addition to giving a friendly message to the user before closing the application, or allowing the user to 'ignore and proceed'.  Do not write try-catch in all your methods. Use it only if there is a possibility that a a specific exception may occur. For example, if you are writing into a file, handle only FileIOException.  Do not write very large try-catch blocks. If required, write separate try-catch for each task you perform and enclose only the specific piece of code inside the try-catch. This will help you find which piece of code generated the exception and you can give specific error message to the user.  You may write your own custom exception classes, if required in your application. Do not derive your custom exceptions from the base class SystemException. Instead, inherit from ApplicationException.

More Related Content

What's hot (13)

Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
Philip Schwarz
 
Templates and Exception Handling in C++
Templates and Exception Handling in C++Templates and Exception Handling in C++
Templates and Exception Handling in C++
Nimrita Koul
 
A Quick Taste of C
A Quick Taste of CA Quick Taste of C
A Quick Taste of C
jeremyrand
 
E learning excel vba programming lesson 3
E learning excel vba programming  lesson 3E learning excel vba programming  lesson 3
E learning excel vba programming lesson 3
Vijay Perepa
 
Best coding practices to follow - to write a code, like a boss
Best coding practices to follow - to write a code, like a bossBest coding practices to follow - to write a code, like a boss
Best coding practices to follow - to write a code, like a boss
Avil Porwal
 
Wade not in unknown waters. Part two.
Wade not in unknown waters. Part two.Wade not in unknown waters. Part two.
Wade not in unknown waters. Part two.
PVS-Studio
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
Connex
 
AVB201.2 Microsoft Access VBA Module 2
AVB201.2 Microsoft Access VBA Module 2AVB201.2 Microsoft Access VBA Module 2
AVB201.2 Microsoft Access VBA Module 2
Dan D'Urso
 
Python syntax
Python syntaxPython syntax
Python syntax
Learnbay Datascience
 
Vba Class Level 1
Vba Class Level 1Vba Class Level 1
Vba Class Level 1
Ben Miu CIM® FCSI A+
 
Naming standards and basic rules in .net coding
Naming standards and basic rules in .net codingNaming standards and basic rules in .net coding
Naming standards and basic rules in .net coding
Naga Harish M
 
ACM init() Spring 2015 Day 1
ACM init() Spring 2015 Day 1ACM init() Spring 2015 Day 1
ACM init() Spring 2015 Day 1
UCLA Association of Computing Machinery
 
Wade not in unknown waters. Part three.
Wade not in unknown waters. Part three.Wade not in unknown waters. Part three.
Wade not in unknown waters. Part three.
PVS-Studio
 
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
Diffing Shotgun Surgery and Divergent Change smells in the two editions of Re...
Philip Schwarz
 
Templates and Exception Handling in C++
Templates and Exception Handling in C++Templates and Exception Handling in C++
Templates and Exception Handling in C++
Nimrita Koul
 
A Quick Taste of C
A Quick Taste of CA Quick Taste of C
A Quick Taste of C
jeremyrand
 
E learning excel vba programming lesson 3
E learning excel vba programming  lesson 3E learning excel vba programming  lesson 3
E learning excel vba programming lesson 3
Vijay Perepa
 
Best coding practices to follow - to write a code, like a boss
Best coding practices to follow - to write a code, like a bossBest coding practices to follow - to write a code, like a boss
Best coding practices to follow - to write a code, like a boss
Avil Porwal
 
Wade not in unknown waters. Part two.
Wade not in unknown waters. Part two.Wade not in unknown waters. Part two.
Wade not in unknown waters. Part two.
PVS-Studio
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
Connex
 
AVB201.2 Microsoft Access VBA Module 2
AVB201.2 Microsoft Access VBA Module 2AVB201.2 Microsoft Access VBA Module 2
AVB201.2 Microsoft Access VBA Module 2
Dan D'Urso
 
Naming standards and basic rules in .net coding
Naming standards and basic rules in .net codingNaming standards and basic rules in .net coding
Naming standards and basic rules in .net coding
Naga Harish M
 
Wade not in unknown waters. Part three.
Wade not in unknown waters. Part three.Wade not in unknown waters. Part three.
Wade not in unknown waters. Part three.
PVS-Studio
 

Similar to N E T Coding Best Practices (20)

Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
mh_azad
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#
Asim Rais Siddiqui
 
Coding standard
Coding standardCoding standard
Coding standard
Shwetketu Rastogi
 
C# conventions & good practices
C# conventions & good practicesC# conventions & good practices
C# conventions & good practices
Tan Tran
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
Raghavan Mohan
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de Javascript
Bernard Loire
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
birbal
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
zone
 
Javascript
JavascriptJavascript
Javascript
guest03a6e6
 
Javascript
JavascriptJavascript
Javascript
vikram singh
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
maheshm1206
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
Adhoura Academy
 
CodingStandardsDoc
CodingStandardsDocCodingStandardsDoc
CodingStandardsDoc
Amol Patole
 
Babitha5.php
Babitha5.phpBabitha5.php
Babitha5.php
banubabitha
 
Php
PhpPhp
Php
WAHEEDA ROOHILLAH
 
Babitha5.php
Babitha5.phpBabitha5.php
Babitha5.php
banubabitha
 
Babitha5.php
Babitha5.phpBabitha5.php
Babitha5.php
banubabitha
 
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
David McCarter
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
mh_azad
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#
Asim Rais Siddiqui
 
C# conventions & good practices
C# conventions & good practicesC# conventions & good practices
C# conventions & good practices
Tan Tran
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
Raghavan Mohan
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de Javascript
Bernard Loire
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
birbal
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
zone
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
maheshm1206
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
Adhoura Academy
 
CodingStandardsDoc
CodingStandardsDocCodingStandardsDoc
CodingStandardsDoc
Amol Patole
 
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
David McCarter
 

More from Abhishek Desai (7)

Rivals4Ever
Rivals4EverRivals4Ever
Rivals4Ever
Abhishek Desai
 
The Device That Used To Be Your Phone
The Device That Used To Be Your PhoneThe Device That Used To Be Your Phone
The Device That Used To Be Your Phone
Abhishek Desai
 
Web 2.0
Web 2.0Web 2.0
Web 2.0
Abhishek Desai
 
Html1
Html1Html1
Html1
Abhishek Desai
 
Sign In Style
Sign In StyleSign In Style
Sign In Style
Abhishek Desai
 
Barcamp
BarcampBarcamp
Barcamp
Abhishek Desai
 
Corporate Blogging D I G I Corp
Corporate  Blogging  D I G I CorpCorporate  Blogging  D I G I Corp
Corporate Blogging D I G I Corp
Abhishek Desai
 

Recently uploaded (20)

What’s New in Web3 Development Trends to Watch in 2025.pptx
What’s New in Web3 Development Trends to Watch in 2025.pptxWhat’s New in Web3 Development Trends to Watch in 2025.pptx
What’s New in Web3 Development Trends to Watch in 2025.pptx
Lisa ward
 
Iobit Driver Booster Pro Crack Free Download [Latest] 2025
Iobit Driver Booster Pro Crack Free Download [Latest] 2025Iobit Driver Booster Pro Crack Free Download [Latest] 2025
Iobit Driver Booster Pro Crack Free Download [Latest] 2025
Mudasir
 
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AIAI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
Buhake Sindi
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...
pranavbodhak
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
Splunk Leadership Forum Wien - 20.05.2025
Splunk Leadership Forum Wien - 20.05.2025Splunk Leadership Forum Wien - 20.05.2025
Splunk Leadership Forum Wien - 20.05.2025
Splunk
 
Wondershare Filmora 14.3.2 Crack + License Key Free for Windows PC
Wondershare Filmora 14.3.2 Crack + License Key Free for Windows PCWondershare Filmora 14.3.2 Crack + License Key Free for Windows PC
Wondershare Filmora 14.3.2 Crack + License Key Free for Windows PC
Mudasir
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
Introducing FME Realize: A New Era of Spatial Computing and AR
Introducing FME Realize: A New Era of Spatial Computing and ARIntroducing FME Realize: A New Era of Spatial Computing and AR
Introducing FME Realize: A New Era of Spatial Computing and AR
Safe Software
 
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk TechniciansOffshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
john823664
 
From Legacy to Cloud-Native: A Guide to AWS Modernization.pptx
From Legacy to Cloud-Native: A Guide to AWS Modernization.pptxFrom Legacy to Cloud-Native: A Guide to AWS Modernization.pptx
From Legacy to Cloud-Native: A Guide to AWS Modernization.pptx
Mohammad Jomaa
 
System Card: Claude Opus 4 & Claude Sonnet 4
System Card: Claude Opus 4 & Claude Sonnet 4System Card: Claude Opus 4 & Claude Sonnet 4
System Card: Claude Opus 4 & Claude Sonnet 4
Razin Mustafiz
 
Build your own NES Emulator... with Kotlin
Build your own NES Emulator... with KotlinBuild your own NES Emulator... with Kotlin
Build your own NES Emulator... with Kotlin
Artur Skowroński
 
AI against disinformation and why it is not enough
AI against disinformation and why it is not enoughAI against disinformation and why it is not enough
AI against disinformation and why it is not enough
Yiannis Kompatsiaris
 
Reducing Bugs With Static Code Analysis php tek 2025
Reducing Bugs With Static Code Analysis php tek 2025Reducing Bugs With Static Code Analysis php tek 2025
Reducing Bugs With Static Code Analysis php tek 2025
Scott Keck-Warren
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
"AI in the browser: predicting user actions in real time with TensorflowJS", ...
"AI in the browser: predicting user actions in real time with TensorflowJS", ..."AI in the browser: predicting user actions in real time with TensorflowJS", ...
"AI in the browser: predicting user actions in real time with TensorflowJS", ...
Fwdays
 
What’s New in Web3 Development Trends to Watch in 2025.pptx
What’s New in Web3 Development Trends to Watch in 2025.pptxWhat’s New in Web3 Development Trends to Watch in 2025.pptx
What’s New in Web3 Development Trends to Watch in 2025.pptx
Lisa ward
 
Iobit Driver Booster Pro Crack Free Download [Latest] 2025
Iobit Driver Booster Pro Crack Free Download [Latest] 2025Iobit Driver Booster Pro Crack Free Download [Latest] 2025
Iobit Driver Booster Pro Crack Free Download [Latest] 2025
Mudasir
 
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AIAI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
AI in Java - MCP in Action, Langchain4J-CDI, SmallRye-LLM, Spring AI
Buhake Sindi
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...
pranavbodhak
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
Splunk Leadership Forum Wien - 20.05.2025
Splunk Leadership Forum Wien - 20.05.2025Splunk Leadership Forum Wien - 20.05.2025
Splunk Leadership Forum Wien - 20.05.2025
Splunk
 
Wondershare Filmora 14.3.2 Crack + License Key Free for Windows PC
Wondershare Filmora 14.3.2 Crack + License Key Free for Windows PCWondershare Filmora 14.3.2 Crack + License Key Free for Windows PC
Wondershare Filmora 14.3.2 Crack + License Key Free for Windows PC
Mudasir
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
Introducing FME Realize: A New Era of Spatial Computing and AR
Introducing FME Realize: A New Era of Spatial Computing and ARIntroducing FME Realize: A New Era of Spatial Computing and AR
Introducing FME Realize: A New Era of Spatial Computing and AR
Safe Software
 
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk TechniciansOffshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
john823664
 
From Legacy to Cloud-Native: A Guide to AWS Modernization.pptx
From Legacy to Cloud-Native: A Guide to AWS Modernization.pptxFrom Legacy to Cloud-Native: A Guide to AWS Modernization.pptx
From Legacy to Cloud-Native: A Guide to AWS Modernization.pptx
Mohammad Jomaa
 
System Card: Claude Opus 4 & Claude Sonnet 4
System Card: Claude Opus 4 & Claude Sonnet 4System Card: Claude Opus 4 & Claude Sonnet 4
System Card: Claude Opus 4 & Claude Sonnet 4
Razin Mustafiz
 
Build your own NES Emulator... with Kotlin
Build your own NES Emulator... with KotlinBuild your own NES Emulator... with Kotlin
Build your own NES Emulator... with Kotlin
Artur Skowroński
 
AI against disinformation and why it is not enough
AI against disinformation and why it is not enoughAI against disinformation and why it is not enough
AI against disinformation and why it is not enough
Yiannis Kompatsiaris
 
Reducing Bugs With Static Code Analysis php tek 2025
Reducing Bugs With Static Code Analysis php tek 2025Reducing Bugs With Static Code Analysis php tek 2025
Reducing Bugs With Static Code Analysis php tek 2025
Scott Keck-Warren
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
"AI in the browser: predicting user actions in real time with TensorflowJS", ...
"AI in the browser: predicting user actions in real time with TensorflowJS", ..."AI in the browser: predicting user actions in real time with TensorflowJS", ...
"AI in the browser: predicting user actions in real time with TensorflowJS", ...
Fwdays
 

N E T Coding Best Practices

  • 1. .NET Coding Best Practices DIGICorp
  • 2. Need for this seminar We all just write code for “working application” Any developer can do that Need to write “Efficient Code” Try to achieve excellence for yourself if not for your company Try to become the ' M ost V alued P rofessional' of your company Writing 'Efficient Code' is an art and you must learn and practice it.
  • 3. Naming Conventions and Standards Pascal Casing - First character of all words are Upper Case and other characters are lower case. Camel Casing - First character of all words, except the first word are Upper Case and other characters are lower case.
  • 4. Use Pascal casing for Class names public class H ello W orld { ... }
  • 5. Use Pascal casing for Method names public class HelloWorld { void S ay H ello(string name) { ... } }
  • 6. Use Camel casing for variables and method parameters public class HelloWorld { int t otal C ount = 0; void SayHello(string n ame) { string f ull M essage = &quot;Hello &quot; + name; ... } }
  • 7. Do not use Hungarian notation to name variables In earlier days most of the programmers liked it - having the data type as a prefix for the variable name and using m_ as prefix for member variables. Example: string m_sName; int nAge; However, in .NET coding standards, this is not reccommended. Usage of datatype and M_ to represent member variables should not be used. All variables should use camel casing.
  • 8. Use Meaningful, descriptive words to name variables Do not use abbreviations. Use name, address, salary etc instead of nam, addr, sal Do not use single character variable names like i, n, x etc. Use names like index, temp One exception in this case would be variables used for iterations in loops for ( int i = 0; i < count; i++ ) { ... } Do not use underscores (_) in variable names. Namespace names should follow the standard pattern <company name>.<product name>.<top level module>.<bottom level module>
  • 9. File name should match with class name For example, for the class HelloWorld, the file name should be helloworld.cs (or, helloworld.vb)
  • 10. Indentation and Spacing Use TAB for indentation. Do not use SPACES. Comments should be in the same level as the code. Curly braces ( {} ) should be in the same level as the code outside the braces. Use one blank line to separate logical groups of code.
  • 11. Which code looks better? bool SayHello (string name) { string fullMessage = &quot;Hello &quot; + name; DateTime currentTime = DateTime.Now; string message = fullMessage + &quot;, the time is : &quot; + currentTime.ToShortTimeString(); MessageBox.Show ( message ); if ( ... ) { // Do something // ... return false; } return true; } bool SayHello (string name) { string fullMessage = &quot;Hello &quot; + name; DateTime currentTime = DateTime.Now; string message = fullMessage + &quot;, the time is : &quot; + currentTime.ToShortTimeString(); MessageBox.Show ( message ); if ( ... ) { // Do something // ... return false; } return true; }
  • 12. Indentation and Spacing There should be one and only one single blank line between each method inside the class. The curly braces should be on a separate line and not in the same line as if, for etc. Good: if ( ... ) { // Do something } Not good: if ( ... ) { // Do something }
  • 13. Indentation and Spacing Use a single space before and after each operator and brackets Good: if ( showResult == true ) { for ( int i = 0; i < 10; i++ ) { // } } Not Good: if(showResult==true) { for(int i= 0;i<10;i++) { // } }
  • 14. Follow the best practices for best programming Avoid having too large files. If a file has more than 300~400 lines of code, you must consider refactoring code into helper classes. Avoid writing very long methods. A method should typically have 1~25 lines of code. If a method has more than 25 lines of code, you must consider re factoring into separate methods.
  • 15. Naming Methods Method name should tell what it does. Do not use misleading names. If the method name is obvious, there is no need of documentation explaining what the method does. Good: void Save PhoneNumber ( string phoneNumber) { // Save the phone number. } Not Good: // This method will save the phone number. void SaveData ( string phoneNumber ) { // Save the phone number. }
  • 16. One job per Method A method should do only 'one job'. Do not combine more than one job in a single method, even if those jobs are very small Good: // Save the address. SaveAddress ( address ); // Send an email to the supervisor to inform that the address is updated. SendEmail ( address, email ); void SaveAddress ( string address ) { // Save the address. // ... } void SendEmail ( string address, string email ) { // Send an email to inform the supervisor that the address is changed. // ... }
  • 17. One job per Method Not Good: // Save address and send an email to the supervisor to inform that the address is updated. SaveAddress ( address, email ); void SaveAddress ( string address, string email ) { // Job 1. // Save the address. // ... // Job 2. // Send an email to inform the supervisor that the address is changed. // ... }
  • 18. Types Use the c# or VB.NET specific types, rather than the alias types defined in System namespace. Good: int age; string name; object contactInfo; Not Good: Int16 age; String name; Object contactInfo;
  • 19. Do not hardcode numbers. Use constants instead. Do not hardcode strings. Use resource files. Avoid using many member variables. Declare local variables and pass it to methods instead of sharing a member variable between methods. If you share a member variable between methods, it will be difficult to track which method changed the value and when.
  • 20. Use of ENUM Use enum wherever required. Do not use numbers or strings to indicate discrete values. Good: enum MailType { Html, PlainText, Attachment } void SendMail (string message, MailType mailType) { switch ( mailType ) { case MailType.Html: // Do something break; case MailType.PlainText: // Do something break; case MailType.Attachment: // Do something break; default: // Do something break; } }
  • 21. Use of ENUM Not Good: void SendMail (string message, MailType mailType) { switch ( mailType ) { case “Html”: // Do something break; case “PlainText”: // Do something break; case “Attachment”: // Do something break; default: // Do something break; } }
  • 22. Do not make the member variables public or protected. Keep them private and expose public/protected Properties . Never hardcode a path or drive name in code. Get the application path programmatically and use relative path. Never assume that your code will run from drive &quot;C:&quot;. You may never know, some users may run it from network or from a &quot;Z:&quot;. In the application start up, do some kind of &quot;self check&quot; and ensure all required files and dependencies are available in the expected locations. Check for database connection in start up, if required. Give a friendly message to the user in case of any problems. If the required configuration file is not found, application should be able to create one with default values. If a wrong value found in the configuration file, application should throw an error or give a message and also should tell the user what are the correct values.
  • 23. Error Messages Error messages should help the user to solve the problem. Never give error messages like &quot;Error in Application&quot;, &quot;There is an error&quot; etc. Instead give specific messages like &quot;Failed to update database. Please make sure the login id and password are correct.&quot; When displaying error messages, in addition to telling what is wrong, the message should also tell what should the user do to solve the problem. Instead of message like &quot;Failed to update database.&quot;, suggest what should the user do: &quot;Failed to update database. Please make sure the login id and password are correct.&quot; Show short and friendly message to the user. But log the actual error with all possible information. This will help a lot in diagnosing problems.
  • 24. Comments Do not write comments for every line of code and every variable declared. Write comments wherever required . But good readable code will require very less comments. If all variables and method names are meaningful, that would make the code very readable and will not need much comments. Less lines of comments will make the code more elegant. But if the code is not clean/readable and there are less comments, that is worse. If you have to use some complex or weird logic for any reason, document it very well with sufficient comments. If you initialize a numeric variable to a special number other than 0, -1 etc, document the reason for choosing that value. The bottom line is, write clean, readable code such a way that it doesn't need any comments to understand. Do a spell check on comments and also make sure proper grammar and punctuation is used.
  • 25. Exception Handling Never do a 'catch exception and do nothing'. If you hide an exception, you will never know if the exception happened or not. In case of exceptions, give a friendly message to the user, but log the actual error with all possible details about the error, including the time it occurred, method and class name etc. Always catch only the specific exception, not generic exception.
  • 26. Good Exception Handling Good: void ReadFromFile ( string fileName ) { try { // read from file. } catch (FileIOException ex) { // log error. // re-throw exception depending on your case. throw; } }
  • 27. Bad Exception Handling Not Good: void ReadFromFile ( string fileName ) { try { // read from file. } catch (Exception ex) { // Catching general exception is bad... we will never know whether it // was a file error or some other error. // Here you are hiding an exception. // In this case no one will ever know that an exception happened. return &quot;&quot;; } }
  • 28. Exception Handling No need to catch the general exception in all your methods. Leave it open and let the application crash. This will help you find most of the errors during development cycle. You can have an application level (thread level) error handler where you can handle all general exceptions. In case of an 'unexpected general error', this error handler should catch the exception and should log the error in addition to giving a friendly message to the user before closing the application, or allowing the user to 'ignore and proceed'. Do not write try-catch in all your methods. Use it only if there is a possibility that a a specific exception may occur. For example, if you are writing into a file, handle only FileIOException. Do not write very large try-catch blocks. If required, write separate try-catch for each task you perform and enclose only the specific piece of code inside the try-catch. This will help you find which piece of code generated the exception and you can give specific error message to the user. You may write your own custom exception classes, if required in your application. Do not derive your custom exceptions from the base class SystemException. Instead, inherit from ApplicationException.