In this blog, I am going to show you a few best practices of ASP.NET programming:
- Always do programming with clean coding and include necessary namespaces.
- Never use inline or internal CSS/JS, go with an external.
- Avoid pre-allocating memory.
- Use #region to group pieces of code together.
- Define global variable at top of all functions and define all private variables at first in the function.
- Avoid writing long methods. If a method has more than 40 lines of code, you must consider refactoring into separate methods.
- To avoid repetitive code create a user control and add user control on-page.
- Specify max length for textbox value. Max length should be the same as the database field size.
- For any text field check “<script></script>” validation.
- Always use trim and HTTP encode method when you get textbox field value.
- Store data in ViewState if you want to use only for one page. If you want to use data in multiple pages then use session.
- If you have a small amount of data, then only store data in ViewState. Don’t store a large amount of data in ViewState.
- For login, check session value for different page in a different browser and if the session value is null, then redirect the user to the login page.
- Using a for each loop instead of a "for" loop makes the code less cluttered. Use a "for" loop only when the index is required.
- Display your custom error page for any unexpected error.
- Do not use misleading names. If the method name is obvious, there is no need for documentation explaining what the method does.
Do
- void SavePhoneNumber ( string phoneNumber )
- {
-
- }
Don’t
-
- void SaveDetails ( string phoneNumber )
- {
-
- }
A method should do only 'one job'. Do not combine more than one jobs in a single method, even if those jobs are very small.
Do
-
- SaveAddress ( address );
-
- SendEmail ( address, email );
- void SaveAddress ( string address )
- {
-
-
- }
- void SendEmail ( string address, string email )
- {
-
-
- }
Don’t
-
-
- SaveAddress ( address, email );
- void SaveAddress ( string address, string email )
- {
-
-
-
-
-
-
- }
- Use a StringBuilder instead of string multiple concatenations are required, to save memory.
- Convert strings to lowercase or uppercase before comparing. This will ensure the string will match even if the string being compared a different case.
Do
- if (string.IsNullOrEmpty(name))
- {
-
- }
Don’t