C sharp coding standrads v1.0

988 views

Published on

Published in: Education, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
988
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
23
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

C sharp coding standrads v1.0

  1. 1. TABLE OF CONTENTS1 INTRODUCTION.........................................................................................................................22 TERMINOLOGY & DEFINITIONS...............................................................................................3 2.1 CAMEL CASE.............................................................................................................................3 2.2 PASCAL CASE............................................................................................................................33 NAMING CONVENTIONS AND STANDARDS...........................................................................4 3.1 VARIABLES................................................................................................................................44 FORMATTING.............................................................................................................................65 CODE COMMENTING.................................................................................................................76 MEMORY MANAGEMENT..........................................................................................................87 LOGGING....................................................................................................................................98 EXCEPTION HANDLING..........................................................................................................109 PROGRAMMING PRACTICES.................................................................................................12
  2. 2. C# Coding Standards1 INTRODUCTIONThis document should be used as a guideline to writing robust and reliable modules and librariesfor project. It focuses on C# coding standards.Reference - http://msdn.microsoft.com/en-us/library/ms229042(VS.85).aspxUncontrolled when copied Page 2 of 17
  3. 3. C# Coding Standards2 TERMINOLOGY & DEFINITIONS2.1 CAMEL CASE A word with the first letter lowercase, and the first letter of each subsequent word-part capitalized. Example: invoiceNumber2.2 PASCAL CASE A word with the first letter capitalized, and the first letter of each subsequent word-part capitalized. Example: InvoiceNumberUncontrolled when copied Page 3 of 17
  4. 4. C# Coding Standards3 NAMING CONVENTIONS AND STANDARDS “c” = camelCase “P” = PascalCase “_” = Prefix with _Underscore “X” = Not Applicable. Identifier Public Protected Internal Private Notes Project File P X X X Match Assembly & Namespace. Source File P X X X Match contained class. Other Files P X X X Apply where possible. Namespace P X X X Partial Project/Assembly match. Class or Struct P P P P Add suffix of subclass. Interface P P P P Prefix with a capital I Generic Class P P P P Use T or K as Type identifier. Method P P P P Use a Verb or Verb-Object pair. Property P P P P Do not prefix with GET or SET Only use Private fields. No Field P P P _c Hungarian Notation! Constant P P P _c Static Field P P P _c Only use Private fields. Enum P P P P Options are also PascalCase. Delegate P P P P Event P P P P Avoid single-character and Inline Variable X X X c enumerated names. Parameter X X X c3.1 VARIABLES • Use Meaningful, descriptive words to name variables. Do not use abbreviations. Good: string invoiceNumber; int sourceCode; Not Good: string num; int code; • Do not use single character variable names Good: for (int invoiceIndex = 0; invoiceIndex < totalInvoices; invoiceIndex++) { //... }Uncontrolled when copied Page 4 of 17
  5. 5. C# Coding Standards Not Good: for (int i = 0; i < total; i++) { //… } • All private member variables must be prefixed with underscore (_) so that they can be identified from other local variables. Do not use underscores (_) for local variable names. Example Member variable – private int _settlementMethodIndicator; Local variable – int settlementMethodIndicator; • Do not use variable names that resemble keywords. Good: private int selectedValue; Not Good: private int select; • Prefix Boolean variables, properties and methods with “is” or similar prefixes. Good: private bool _isEnabled; Not Good: private bool _enabled; • Namespace names should follow the standard pattern <company name>.<product name>.<top level module>.<bottom level module> Example – IATA.SIS.Core.LoggingUncontrolled when copied Page 5 of 17
  6. 6. C# Coding Standards4 FORMATTING • Never declare more than 1 namespace per file. • Avoid putting multiple classes in a single file. • Always place curly braces ( { and } ) on a new line. • Always use curly braces ( { and } ) in conditional statements. • Declare each variable independently – not in the same statement. • Group internal class implementation by type in the following order:  Member variables.  Constructors & Finalizers.  Nested Enums, Structs, and Classes.  Properties  Methods • Sequence declarations within type groups based upon access modifier and visibility:  Public  Protected  Internal  Private • Append folder-name to namespace for source files within sub-folders. • Recursively indent all code blocks contained within braces. • Indent size should be 2 spaces (and not the default 4 spaces). • Use white space (CR/LF, spaces, etc) liberally to separate and organize code. • Never use the Tab character for indenting. Setup the IDE to insert spaces for the Tab character.Uncontrolled when copied Page 6 of 17
  7. 7. C# Coding Standards5 CODE COMMENTING • All comments should be written in U.S. English._ • Use // or /// but never /*------*/ • Do not “flowerbox” comment blocks Example: Not Good //-------------------------------------------------- // Comment Block //-------------------------------------------------- • Use inline-comments to explain assumptions, known issues, and algorithm insights. • Do not use inline-comments to explain obvious code. Well written code is self documenting. • Include Task-List keyword flags to enable comment-filtering. Example: //TODO: Place database code here // TODO: Fix this code. • Always apply C# comment-blocks /// to public, protected and internal declarations. • Only use C# comment-blocks for documenting the API. • Always include <summary> comments. Include <param>, <return> and <exception> comment sections where applicable. • Include <see cref=””> and <seeAlso cref=””> where possible. • Always add CDATA tags to comments containing code and other embedded markup in order to avoid encoding issues.Uncontrolled when copied Page 7 of 17
  8. 8. C# Coding Standards6 MEMORY MANAGEMENT • Avoid boxing and un-boxing. • Avoid type casting as much possible. • Use strong typing wherever possible. • Do not repeatedly call the same method on an object in a loop. Instead store the return value of the method in a local variable and use it.Uncontrolled when copied Page 8 of 17
  9. 9. C# Coding Standards7 LOGGING • Log component should be written such a way that in future you can change it easily to log to Windows Event Log, Oracle or Email to administrator or to a File etc. without any change in any other part of the application. • Always use logging component to log errors, warning and traces. • If you configure to log errors, it should only log errors. But if you configure to log traces, it should record all (errors, warnings and trace). • Use the log component extensively throughout the code to record errors, warning and even trace messages that can help you trouble shoot a problem. • Follow hierarchy naming convention for logger. Naming convention can be FunctionalArea.Module. Log4Net supports configuration settings to be inherited when hierarchical naming convention is followed. • One way of improving performance can be checking for IsDebugEnabled before actually logging. However, we can create static logger to further increase the performance as any change in configuration will require application to be restarted.Uncontrolled when copied Page 9 of 17
  10. 10. C# Coding Standards8 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. Lot of developers use this handy method to ignore non significant errors. You should always try to avoid exceptions by checking all the error conditions programmatically. In any case, catching an exception and doing nothing is not allowed. In the worst case, you should log the exception and proceed. • 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 name, class name, stack trace, etc. • Always catch only the specific exception, not generic exception. Good: void ReadFromFile(string fileName) { try { // read from file. } catch (DataException ex) { // log error. // re-throw exception depending on your case. throw; } } 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 ""; } } • 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.Uncontrolled when copied Page 10 of 17
  11. 11. C# Coding Standards • When you re throw an exception, use the throw statement without specifying the original exception. This way, the original call stack is preserved. Good: catch { // do whatever you want to handle the exception throw; } Not Good: catch (Exception ex) { // do whatever you want to handle the exception throw ex; } • Do not write try-catch in all your methods. Use it only if there is a possibility that a specific exception may occur and it cannot be prevented by any other means. For example, if you want to insert a record if it does not already exists in database, you should try to select record using the key. Some developers try to insert a record without checking if it already exists. If an exception occurs, they will assume that the record already exists. This is strictly not allowed. You should always explicitly check for errors rather than waiting for exceptions to occur. On the other hand, you should always use exception handlers while you communicate with external systems like network, hardware devices etc. Such systems are subject to failure anytime and error checking is not usually reliable. In those cases, you should use exception handlers and try to recover from error. • 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. • 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. • Do use try-finally and avoid using try-catch for cleanup code. In well-written exception code, try-finally is far more common than try-catch. The purpose of a catch clause is to allow you to handle exceptions (for example, by logging a non-fatal error). The purpose of a finally clause is to allow you to execute cleanup code regardless of whether an exception was thrown. If you allocate expensive or limited resources such as database connections or streams, you should put the code to release them inside a finally block.Uncontrolled when copied Page 11 of 17
  12. 12. C# Coding Standards9 PROGRAMMING PRACTICES • Do not use magic numbers. Use constants instead. • 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. • 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 SaveInvoiceNumber(string invoiceNumber) { // Save the invoice number. } Not Good: // This method will save the invoice number. void SaveDetails(string invoiceNumber) { // Save the invoice number. } • 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 address updated. SendEmail(address, email); void SaveAddress(string address) { // Job 1. // Save the address. // ... } void SendEmail(string email) { // Job 1. //Send an email to inform supervisor that address is changed. } Not Good: SaveAddress(address, email);Uncontrolled when copied Page 12 of 17
  13. 13. C# Coding Standards 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. // ... } • Use the checked keyword to control the overflow-checking context for integral-type arithmetic operations and conversions. • Always use the most restrictive data type for parameters. For example, when we pass a value to a method that describes the size of a data structure, use unsigned integer rather than integer. • Never, ever hardcode passwords or other sensitive information into your application. • Always validate input that is used to generate SQL queries. • Do not display exception information: it provides any would-be attacker with valuable clues. • Do not use your own encryption algorithms. Use the System.Security.Cryptography classes. • Give your assemblies strong names to store in GAC in case the assemblies are going to be shared across multiple sub-systems of the application. • Do not store sensitive information in XML or other configuration files. • 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. • 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. • Consider using Code Contracts in .NET 4 to check validity for input parameters. Good: if (memberType == eMemberTypes.Registered) { // Registered user… do something… } else if (memberType == eMemberTypes.Guest) { // Guest user... do something… } else {Uncontrolled when copied Page 13 of 17
  14. 14. C# Coding Standards // Un expected user type. Throw an exception throw new InvalidArgumentException("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. } • Do not hardcode numbers. Use constants instead. Declare constant in the top of the 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. • Do not hardcode strings. Use resource files. • 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") { //… } • Use String.IsNullOrEmpty instead of “” Good: if (string.IsNullOrEmpty(name)) { // do something } Not Good: if (name == “”) { // do something }Uncontrolled when copied Page 14 of 17
  15. 15. C# Coding Standards • Avoid using member variables. Declare local variables wherever necessary and pass it to other 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.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 "Html": // Do something break; case "PlainText": // Do something break; case "Attachment": // Do something break; default: // Do something break; } }Uncontrolled when copied Page 15 of 17
  16. 16. C# Coding Standards • Do not make the member variables public or protected. Keep them private and expose public/protected Properties. • The event handler should not contain the code to perform the required action. Rather call another method from the event handler. • 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. • 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:". • 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. • 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 the user should 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. • Do not have more than one class in a single file. • Have your own templates for each of the file types in Visual Studio. You can include your company name, copy right information etc in the template. You can view or edit the Visual Studio file templates in the folder C:Program FilesMicrosoft Visual Studio 8Common7IDEItemTemplatesCacheCSharp1033. (This folder has the templates for C#, but you can easily find the corresponding folders or any other language) • 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. • 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. • 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. • 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 validUncontrolled when copied Page 16 of 17
  17. 17. C# Coding Standards 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”. • Use the AssemblyInfo file to fill information like version number, description, company name, copyright notice etc. • Logically organize all the classes into appropriate namespaces. • Always make use of using blocks while dealing with external/unmanaged resources that need to released after you are done using them.Uncontrolled when copied Page 17 of 17

×