SlideShare a Scribd company logo
2
Most read
13
Most read
19
Most read
Coding best practices The Jaxara IT Ltd. Mahmudul Haque Azad
Coding… Anybody can write code. With a few months of programming experience, you can write 'working applications'. Making it work is easy, but doing it the right way requires more work, than just making it work.  Believe it, majority of the programmers write 'working code', but not ‘good code'. Writing 'good code' is an art and you must learn and practice it.  Following are the characteristics of good code. Reliable Maintainable Efficient If your code is not reliable and maintainable, you (and your company) will be spending lot of time to identify issues, trying to understand code etc throughout the life of your application.
Naming Conventions and Standards The terms  Pascal Casing  and  Camel Casing  are used throughout this document.  Pascal Casing  - First character of all words are Upper Case and other characters are lower case.  Example:  B ack C olor Camel Casing -  First character of all words,  except the first word  are Upper Case and other characters are lower case. Example:  b ack C olor
Naming Conventions and Standards (cont.) 1. Use  Pascal  casing for  Class   names   public class  H ello W orld { ... } 2 .  Use  Pascal  casing for   Method   names   void  S ay H ello (string  name ) { ... } 3.  Use  Camel  casing for   variables   and   method parameters   int  t otal C ount   = 0; void  S ay H ello( string  name) { string  f ull M essage  = "Hello "  +  name ; ... } 4.  Use the prefix “ I ” with Camel  Casing  for  interfaces   ( Example:  I Entity  )
Naming Conventions and Standards (cont.) 5. Use  meaningful , descriptive words to name variables. Do not use abbreviations. Good string   address int   salary Not Good: string   nam string   addr int   sal   6.  Do not use  single character variable names like i, n, s 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++ ) { ... } If the variable is used only as a counter for iteration and is not used anywhere else in the loop,  many people still like to use a single char variable (i) instead of inventing a different suitable name.
Naming Conventions and Standards (cont.) 7. Do not use underscores (_) for local variable names.  8. All member variables must be prefixed with underscore (_) so that they can be identified from other local variables. 9. Do not use variable names that resemble keywords. 10. Prefix  boolean  variables, properties and methods with “ is ” or similar prefixes. Ex:  private bool _isFinished 11. File name should match with class name. For example, for the class HelloWorld, the file name should be HelloWorld.cs (or, HelloWorld.vb)  12. Use Pascal Case for file names.
Naming Conventions and Standards 13. Use appropriate prefix for the UI elements so that you can identify them from the rest of the variables. A brief list is given below. Since .NET has given several controls, you may have to arrive at a complete list of standard prefixes for each of the controls (including third party controls) you are using. Example:
Naming Conventions and Standards 1. Use TAB for indentation. Do not use SPACES.  Define the Tab size as 4. 2. Comments should be in the same level as the code (use the same level of indentation).  Good: // Format a message and display string  fullMessage = &quot;Hello &quot; + name; DateTime  currentTime = DateTime.Now; string  message = fullMessage + &quot;, Thanks &quot;  MessageBox .Show ( message ); Not Good: // Format a message and display string  fullMessage = &quot;Hello &quot; + name; DateTime  currentTime = DateTime.Now; string  message = fullMessage + &quot;, Thanks ”  MessageBox .Show ( message );
Naming Conventions and Standards 3. Curly braces (  {}  ) should be in the same level as the code outside the braces. 4. There should be one and only one single blank line between each method inside  the class.  5. 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 }
Naming Conventions and Standards 6. Use one blank line to separate logical groups of code.  Good: 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 ; } Not Good: 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 ; }
Naming Conventions and Standards 7. 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++) { // } } 8.   Keep private member variables, properties and methods in the top of the file and public members in the bottom.
Indentation and Spacing 9. Use  #region  to group related pieces of code together. If you use proper grouping using #region , the page should like this when all definitions are collapsed.
Good Programming practices 1. 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.  2. Method name should tell what it does. Do not use mis-leading names. If the method name is  obvious, there is no need of documentation explaining what the method does.  Good:   void  SavePhoneNumber (  string  phoneNumber ) { // Save the phone number. } Not Good:  // This method will save the phone number. void  SaveDetails (  string  phoneNumber ) { // Save the phone number. }
Good Programming practices 3. 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. // ... } 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. // ... }
Good Programming practices 4. Use the c# or VB.NET specific types (aliases), rather than the types defined in System namespace.   int  age;  (not  I nt 16 ) string  name;  (not  S tring ) object  contactInfo; (not  O bject ) 5. Do not hardcode numbers. Use constants instead. Declare constant in the top of the file or in a separate constant file and use it in your code. However, using constants are also not recommended. You should use the constants in the config file or database so that you can change it later. Declare them as  constants only if you are sure this value will never need to be changed. 6. Do not hardcode strings. Use resource files i.e.  a separate constant file. 7. Convert strings to lowercase or upper case before comparing. This will ensure the string will match even if the string being compared has a different case. if ( name.ToLower() == “john” ) {   //… }
Good Programming practices 9.  Always watch for unexpected values. For example, if you are using a parameter with 2 possible values, never  assume that if one is not matching then the only possibility is the other value. Good: if  ( memberType == eMemberTypes.Registered ) { // Registered user… do something… } else if  ( memberType == eMemberTypes.Guest ) { // Guest user... do something… } else { // Un expected user type. Throw an exception throw new Exception (“Un expected value “ + memberType.ToString() + “’.”) // If we introduce a new user type in future, we can easily find  // the problem here. } Not Good: if  ( memberType == eMemberTypes.Registered ) { // Registered user… do something… } else { // Guest user... do something… // If we introduce another user type in future, this code will  // fail and will not be noticed. }
Good Programming practices 10. Use String.Empty instead of “” Good: If ( name == String.Empty ) { // do something } Not Good: If ( name == “” ) { // do something } 11. Do not make the member variables public or protected. Keep them private and expose public/protected Properties.  12. The event handler should not contain the code to perform the required action. Rather call another method from the event handler. 13. Do not programmatically click a button to execute the same action you have written in the button click event. Rather, call the same method which is called by the button click event handler. 14. Never hardcode a path or drive name in code. Get the application path programmatically and use relative path.
Good Programming practices 15. 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 ; } } Not Good:  void  SendMail ( string  message,  string  mailType) { switch  ( mailType ) { case  &quot;Html&quot;: // Do something break ; case  &quot;PlainText&quot;: // Do something break ; case  &quot;Attachment&quot;: // Do something break ; default : // Do something break ; } }
Good Programming practices 16. 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.“ 17.  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. 18. Do not have more than one class in a single file.   19. Avoid having very large files. If a single file has more than 1000 lines of code, it is a good candidate for refactoring. Split them logically into two or more classes. 20. Avoid public methods and properties, unless they really need to be accessed from outside the class. Use “ internal ” if they are accessed only within the same assembly.
Good Programming practices 21. Avoid passing too many parameters to a method. If you have more than 4~5 parameters, it is a good candidate to define a class or structure. 22. If you have a method returning a collection, return an empty collection instead of null, if you have no data to return. For example, if you have a method returning an ArrayList, always return a valid ArrayList. If you have no items to return, then return a valid ArrayList with 0 items. This will make it easy for the calling application to just check for the “count” rather than doing an additional check for “null”. 23. If you are opening database connections, sockets, file stream etc, always close them in the  finally  block. This will ensure that even if an exception occurs after opening the connection, it will be safely closed in the  finally  block. 24. Declare variables as close as possible to where it is first used. Use one variable declaration per line.
Good Programming practices 25.   Use StringBuilder class instead of String when you have to manipulate string objects in a loop. The String object works in weird way in .NET. Each time you append a string, it is actually discarding the old string object and recreating a new object, which is a relatively expensive operations. Consider the following example: public   string  ComposeMessage ( string [] lines) {      string  message =  string .Empty;      for ( int  i = 0; i < lines.Length; i++)     {         message += lines [i];      }     return  message; } In the above example, it may look like we are just appending to the string object ‘message’. But what is happening in reality is, the string object is discarded in each iteration and recreated and appending the line to it. If your loop has several iterations, then it is a good idea to use StringBuilder class instead of String object. See the example where the String object is replaced with StringBuilder. public   string  ComposeMessage ( string [] lines) {      StringBuilder  message =  new   StringBuilder ();      for ( int  i = 0; i < lines.Length; i++)      {        message.Append( lines[i] );       }      return  message.ToString(); }
Good Programming practices 26.   Do not use session variables throughout the code. Use session variables only within the classes and expose methods to access the value stored in the session variable. A class can access session using   System.Web.HttpCOntext.Current.Session 27. Do not store large objects in session. Storing large objects in session may consume lot of server memory depending on the number of users. 28. Always use style sheet to control the look and feel of the pages. Never specify font name and font size in any of the pages. Use appropriate style class. This will help you to change the UI of your application easily in future. Also, if you like to support customizing the UI for each customer, it is just a matter of developing another style sheet for them
Good Programming practices 29. Never access database from the UI pages. Always have a data layer class which performs all the database related tasks. This will help you support or migrate to another database back end easily. 30. Use try-catch in your data layer to catch all database exceptions. This exception handler should record all exceptions from the database. The details recorded should include the name of the command being executed, stored proc name, parameters, connection string used etc. After recording the exception, it could be re thrown so that another layer in the application can catch it and take appropriate action.
Thank you!

More Related Content

PPTX
Coding standards for java
PPTX
Cloud Computing: Virtualization
PDF
La Gestion De Projets Pour Les Nuls.pdf
PPTX
Google classroom
PPTX
Cyber Security PPT.pptx
PPTX
Introduction to Machine Learning
PPTX
Coding standards
PPT
Time Domain and Frequency Domain
Coding standards for java
Cloud Computing: Virtualization
La Gestion De Projets Pour Les Nuls.pdf
Google classroom
Cyber Security PPT.pptx
Introduction to Machine Learning
Coding standards
Time Domain and Frequency Domain

What's hot (20)

PPTX
Coding standards
PPTX
Coding conventions
PDF
Methods in Java
PPTX
Coding standards and guidelines
PDF
C# conventions & good practices
PPTX
Collections in-csharp
PDF
Java I/o streams
PPT
DOT Net overview
PPSX
Data Types & Variables in JAVA
PPTX
C# classes objects
PPT
Introduction To C#
PPTX
clean code book summary - uncle bob - English version
PPTX
Solid principles
PPSX
Coding standard
PDF
ITFT-Constants, variables and data types in java
PDF
Javascript essentials
PPT
Introduction to c#
PPT
Coding standard
PDF
Clean code
Coding standards
Coding conventions
Methods in Java
Coding standards and guidelines
C# conventions & good practices
Collections in-csharp
Java I/o streams
DOT Net overview
Data Types & Variables in JAVA
C# classes objects
Introduction To C#
clean code book summary - uncle bob - English version
Solid principles
Coding standard
ITFT-Constants, variables and data types in java
Javascript essentials
Introduction to c#
Coding standard
Clean code
Ad

Similar to Coding Best Practices (20)

PPT
Coding Standards & Best Practices for iOS/C#
PPT
N E T Coding Best Practices
DOCX
CodingStandardsDoc
PPTX
Naming Standards, Clean Code
PPTX
Best Coding Practices in Java and C++
PDF
In-Depth Guide On WordPress Coding Standards For PHP & HTML
PPTX
Coding standards
PPTX
Back-2-Basics: .NET Coding Standards For The Real World
PPT
c-coding-standards-and-best-programming-practices.ppt
PPT
Codings Standards
PPTX
Back-2-Basics: .NET Coding Standards For The Real World
PPT
Lecture No 13.ppt
PPT
JAVA Tutorial- Do's and Don'ts of Java programming
PPT
JAVA Tutorial- Do's and Don'ts of Java programming
PPT
Best Practices of Software Development
PPT
Naming standards and basic rules in .net coding
PDF
iOS best practices
PDF
Good Coding Practices with JavaScript
PPT
The JavaScript Programming Language
PPT
Javascript by Yahoo
 
Coding Standards & Best Practices for iOS/C#
N E T Coding Best Practices
CodingStandardsDoc
Naming Standards, Clean Code
Best Coding Practices in Java and C++
In-Depth Guide On WordPress Coding Standards For PHP & HTML
Coding standards
Back-2-Basics: .NET Coding Standards For The Real World
c-coding-standards-and-best-programming-practices.ppt
Codings Standards
Back-2-Basics: .NET Coding Standards For The Real World
Lecture No 13.ppt
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Best Practices of Software Development
Naming standards and basic rules in .net coding
iOS best practices
Good Coding Practices with JavaScript
The JavaScript Programming Language
Javascript by Yahoo
 
Ad

Recently uploaded (20)

PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Machine learning based COVID-19 study performance prediction
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
 
PDF
cuic standard and advanced reporting.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
 
PDF
Assigned Numbers - 2025 - BluetoothÂŽ Document
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPT
Teaching material agriculture food technology
PPTX
Machine Learning_overview_presentation.pptx
PDF
Empathic Computing: Creating Shared Understanding
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
 
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Programs and apps: productivity, graphics, security and other tools
Machine learning based COVID-19 study performance prediction
MIND Revenue Release Quarter 2 2025 Press Release
sap open course for s4hana steps from ECC to s4
Encapsulation_ Review paper, used for researhc scholars
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
 
cuic standard and advanced reporting.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
The AUB Centre for AI in Media Proposal.docx
 
Assigned Numbers - 2025 - BluetoothÂŽ Document
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Teaching material agriculture food technology
Machine Learning_overview_presentation.pptx
Empathic Computing: Creating Shared Understanding
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Network Security Unit 5.pdf for BCA BBA.
The Rise and Fall of 3GPP – Time for a Sabbatical?
 

Coding Best Practices

  • 1. Coding best practices The Jaxara IT Ltd. Mahmudul Haque Azad
  • 2. Coding… Anybody can write code. With a few months of programming experience, you can write 'working applications'. Making it work is easy, but doing it the right way requires more work, than just making it work. Believe it, majority of the programmers write 'working code', but not ‘good code'. Writing 'good code' is an art and you must learn and practice it. Following are the characteristics of good code. Reliable Maintainable Efficient If your code is not reliable and maintainable, you (and your company) will be spending lot of time to identify issues, trying to understand code etc throughout the life of your application.
  • 3. Naming Conventions and Standards The terms Pascal Casing and Camel Casing are used throughout this document. Pascal Casing - First character of all words are Upper Case and other characters are lower case. Example: B ack C olor Camel Casing - First character of all words, except the first word are Upper Case and other characters are lower case. Example: b ack C olor
  • 4. Naming Conventions and Standards (cont.) 1. Use Pascal casing for Class names public class H ello W orld { ... } 2 . Use Pascal casing for Method names void S ay H ello (string name ) { ... } 3. Use Camel casing for variables and method parameters int t otal C ount = 0; void S ay H ello( string name) { string f ull M essage = &quot;Hello &quot; + name ; ... } 4. Use the prefix “ I ” with Camel Casing for interfaces ( Example: I Entity )
  • 5. Naming Conventions and Standards (cont.) 5. Use meaningful , descriptive words to name variables. Do not use abbreviations. Good string address int salary Not Good: string nam string addr int sal 6. Do not use single character variable names like i, n, s 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++ ) { ... } If the variable is used only as a counter for iteration and is not used anywhere else in the loop, many people still like to use a single char variable (i) instead of inventing a different suitable name.
  • 6. Naming Conventions and Standards (cont.) 7. Do not use underscores (_) for local variable names. 8. All member variables must be prefixed with underscore (_) so that they can be identified from other local variables. 9. Do not use variable names that resemble keywords. 10. Prefix boolean variables, properties and methods with “ is ” or similar prefixes. Ex: private bool _isFinished 11. File name should match with class name. For example, for the class HelloWorld, the file name should be HelloWorld.cs (or, HelloWorld.vb) 12. Use Pascal Case for file names.
  • 7. Naming Conventions and Standards 13. Use appropriate prefix for the UI elements so that you can identify them from the rest of the variables. A brief list is given below. Since .NET has given several controls, you may have to arrive at a complete list of standard prefixes for each of the controls (including third party controls) you are using. Example:
  • 8. Naming Conventions and Standards 1. Use TAB for indentation. Do not use SPACES. Define the Tab size as 4. 2. Comments should be in the same level as the code (use the same level of indentation). Good: // Format a message and display string fullMessage = &quot;Hello &quot; + name; DateTime currentTime = DateTime.Now; string message = fullMessage + &quot;, Thanks &quot; MessageBox .Show ( message ); Not Good: // Format a message and display string fullMessage = &quot;Hello &quot; + name; DateTime currentTime = DateTime.Now; string message = fullMessage + &quot;, Thanks ” MessageBox .Show ( message );
  • 9. Naming Conventions and Standards 3. Curly braces ( {} ) should be in the same level as the code outside the braces. 4. There should be one and only one single blank line between each method inside the class. 5. 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 }
  • 10. Naming Conventions and Standards 6. Use one blank line to separate logical groups of code. Good: 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 ; } Not Good: 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 ; }
  • 11. Naming Conventions and Standards 7. 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++) { // } } 8. Keep private member variables, properties and methods in the top of the file and public members in the bottom.
  • 12. Indentation and Spacing 9. Use #region to group related pieces of code together. If you use proper grouping using #region , the page should like this when all definitions are collapsed.
  • 13. Good Programming practices 1. 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. 2. Method name should tell what it does. Do not use mis-leading names. If the method name is obvious, there is no need of documentation explaining what the method does. Good: void SavePhoneNumber ( string phoneNumber ) { // Save the phone number. } Not Good: // This method will save the phone number. void SaveDetails ( string phoneNumber ) { // Save the phone number. }
  • 14. Good Programming practices 3. 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. // ... } 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. // ... }
  • 15. Good Programming practices 4. Use the c# or VB.NET specific types (aliases), rather than the types defined in System namespace. int age; (not I nt 16 ) string name; (not S tring ) object contactInfo; (not O bject ) 5. Do not hardcode numbers. Use constants instead. Declare constant in the top of the file or in a separate constant file and use it in your code. However, using constants are also not recommended. You should use the constants in the config file or database so that you can change it later. Declare them as constants only if you are sure this value will never need to be changed. 6. Do not hardcode strings. Use resource files i.e. a separate constant file. 7. Convert strings to lowercase or upper case before comparing. This will ensure the string will match even if the string being compared has a different case. if ( name.ToLower() == “john” ) { //… }
  • 16. Good Programming practices 9. Always watch for unexpected values. For example, if you are using a parameter with 2 possible values, never assume that if one is not matching then the only possibility is the other value. Good: if ( memberType == eMemberTypes.Registered ) { // Registered user… do something… } else if ( memberType == eMemberTypes.Guest ) { // Guest user... do something… } else { // Un expected user type. Throw an exception throw new Exception (“Un expected value “ + memberType.ToString() + “’.”) // If we introduce a new user type in future, we can easily find // the problem here. } Not Good: if ( memberType == eMemberTypes.Registered ) { // Registered user… do something… } else { // Guest user... do something… // If we introduce another user type in future, this code will // fail and will not be noticed. }
  • 17. Good Programming practices 10. Use String.Empty instead of “” Good: If ( name == String.Empty ) { // do something } Not Good: If ( name == “” ) { // do something } 11. Do not make the member variables public or protected. Keep them private and expose public/protected Properties. 12. The event handler should not contain the code to perform the required action. Rather call another method from the event handler. 13. Do not programmatically click a button to execute the same action you have written in the button click event. Rather, call the same method which is called by the button click event handler. 14. Never hardcode a path or drive name in code. Get the application path programmatically and use relative path.
  • 18. Good Programming practices 15. 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 ; } } Not Good: void SendMail ( string message, string mailType) { switch ( mailType ) { case &quot;Html&quot;: // Do something break ; case &quot;PlainText&quot;: // Do something break ; case &quot;Attachment&quot;: // Do something break ; default : // Do something break ; } }
  • 19. Good Programming practices 16. 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.“ 17. 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. 18. Do not have more than one class in a single file. 19. Avoid having very large files. If a single file has more than 1000 lines of code, it is a good candidate for refactoring. Split them logically into two or more classes. 20. Avoid public methods and properties, unless they really need to be accessed from outside the class. Use “ internal ” if they are accessed only within the same assembly.
  • 20. Good Programming practices 21. Avoid passing too many parameters to a method. If you have more than 4~5 parameters, it is a good candidate to define a class or structure. 22. If you have a method returning a collection, return an empty collection instead of null, if you have no data to return. For example, if you have a method returning an ArrayList, always return a valid ArrayList. If you have no items to return, then return a valid ArrayList with 0 items. This will make it easy for the calling application to just check for the “count” rather than doing an additional check for “null”. 23. If you are opening database connections, sockets, file stream etc, always close them in the finally block. This will ensure that even if an exception occurs after opening the connection, it will be safely closed in the finally block. 24. Declare variables as close as possible to where it is first used. Use one variable declaration per line.
  • 21. Good Programming practices 25. Use StringBuilder class instead of String when you have to manipulate string objects in a loop. The String object works in weird way in .NET. Each time you append a string, it is actually discarding the old string object and recreating a new object, which is a relatively expensive operations. Consider the following example: public string ComposeMessage ( string [] lines) {     string message = string .Empty;     for ( int i = 0; i < lines.Length; i++)     {        message += lines [i];     }     return message; } In the above example, it may look like we are just appending to the string object ‘message’. But what is happening in reality is, the string object is discarded in each iteration and recreated and appending the line to it. If your loop has several iterations, then it is a good idea to use StringBuilder class instead of String object. See the example where the String object is replaced with StringBuilder. public string ComposeMessage ( string [] lines) {      StringBuilder message = new StringBuilder ();      for ( int i = 0; i < lines.Length; i++)      {        message.Append( lines[i] );      }      return message.ToString(); }
  • 22. Good Programming practices 26. Do not use session variables throughout the code. Use session variables only within the classes and expose methods to access the value stored in the session variable. A class can access session using System.Web.HttpCOntext.Current.Session 27. Do not store large objects in session. Storing large objects in session may consume lot of server memory depending on the number of users. 28. Always use style sheet to control the look and feel of the pages. Never specify font name and font size in any of the pages. Use appropriate style class. This will help you to change the UI of your application easily in future. Also, if you like to support customizing the UI for each customer, it is just a matter of developing another style sheet for them
  • 23. Good Programming practices 29. Never access database from the UI pages. Always have a data layer class which performs all the database related tasks. This will help you support or migrate to another database back end easily. 30. Use try-catch in your data layer to catch all database exceptions. This exception handler should record all exceptions from the database. The details recorded should include the name of the command being executed, stored proc name, parameters, connection string used etc. After recording the exception, it could be re thrown so that another layer in the application can catch it and take appropriate action.