Fri
13
Jan '06
Courtesy: Google Date Written: Friday, December 02, 2005.NET Coding Practices
Errors may occur many ways – the network connection might go down, the printer might run out of paper and so forth. As the programmer, it’s your fault when these things happen, at the very least, your program must do the following • In some way notify the user of the problem • Allow the user to save his/her work if appropriate • Allow users to gracefully exit the program if they think it necessary 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. 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. Validations Checking for all conditions and assignments where a null value can occur. Null checking for all function parameter values For lists and combos, always consider the case when the number of elements is zero. Example situations are setting the selected index, or getting the selected value. In the application start up, do some kind of “self check” 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 should help the user to solve the problem. Never give error messages like “Error in Application”, “There is an error” etc. Instead give specific messages like “Failed to update database. Please make sure the login id and password are correct.” 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 “Failed to update database.”, suggest what should the user do: “Failed to update database. Please make sure the login id and password are correct.” 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 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. Put comments on every functions/class/code which you think it may be not understandable for others. Comments should be in the same level as the code If you initialize a numeric variable to a special number other than 0, -1 etc, document the reason for choosing that value. On top of the Your Code put something like this : // File Name :// Purpose : [requirement code] // Author : // Date : // Version : Naming conversions and standards Do not use Hungarian Notation User Pascal Casing for Class Names and Method names Use meaningful, descriptive words to name variables 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. Identifier Case Example Class Pascal AppDomain Enum type Pascal ErrorLevel Enum values Pascal FatalError Event Pascal ValueChange Exception class Pascal WebException Note Always ends with the suffix Exception. Read-only Static field Pascal RedValue Interface Pascal IDisposable Note Always begins with the prefix I. Method Pascal ToString Namespace Pascal System.Drawing Parameter Camel typeName Property Pascal BackColor Protected instance field Camel redValue Note Rarely used. A property is preferable to using a protected instance field. Public instance field Pascal RedValue Note Rarely used. A property is preferable to using a public instance field. Formatting Use TAB for indentation. Do not use SPACE Curly braces ( {} ) should be in the same level as the code outside the braces. Use one blank line to separate logical group of code. 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. Use a single space before and after each operator and brackets. 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. Good Practices Do not make the member variables public or protected. Keep them private and expose public/protected Properties. Strictly avoid code duplication. Whenever a utility function is added, check if it can be used by other modules. if yes, include it as a shared function in a common class. 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. 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. Use the c# or VB.NET specific types, rather than the alias types defined in System namespace. 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 enum wherever required. Do not use numbers or strings to indicate discrete values. 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 “C:”. You may never know, some users may run it from network or from a “Z:”.public class HelloWorld { bool SayHello ( string name ) { string fullMessage = “Hello “ + name; DateTime currentTime = DateTime.Now; string message = fullMessage + “, the time is : “ + currentTime.ToShortTimeString(); MessageBox.Show ( message ); if ( … ) { // Do something // … return false; } return true; } }

Leave a Reply