Google
 

Friday, May 25, 2007

C♯ Coding Style Guide

C♯ Coding Style Guide

  1. Keep your classes/files short, don't exceed 2000 LOC, divide your code up, make structures clearer.
  2. Create a directory for every namespace.
  3. When an expression will not fit on a single line, break it up according to these general principles:
     Break after a comma.
     Break after an operator.
     Prefer higher-level breaks to lower-level breaks.
     Align the new line with the beginning of the expression at the same level on the previous line
  4. Don't use spaces for indentation - use tabs!
  5. Block comments should usually be avoided. For descriptions use of the /// comments to give C ♯ standard
    descriptions is recommended. When you wish to use block comments you should use the following style :
    /* Line 1
    * Line 2
    * Line 3
    */
    As this will set off the block visually from code for the (human) reader.
  6. You should use the // comment style to "comment out" code (SharpDevelop has a key for it, Alt+/) . It may
    be used for commenting sections of code too. A rule of thumb says that generally, the length of a comment should not exceed the length of the code explained by too much, as this is an indication of too complicated, potentially buggy, code.
  7. These comments are formally single line C♯ comments containing XML tags. They follow this
    pattern for single line comments:
    /// <summary>
    /// This class...
    /// </summary>
    Multiline XML comments follow this pattern:
    /// <exception cref="BogusException">
    /// This exception gets thrown as soon as a
    /// Bogus flag gets set.
    /// </exception>
    All lines must be preceded by three slashes to be accepted as XML comment lines.
    Tags fall into two categories:
    • Documentation items
    • Formatting/Referencing
  8. One declaration per line is recommended since it encourages commenting
  9. Try to initialize local variables as soon as they are declared.Note: If you initialize a dialog try to use the using statement:
    using (OpenFileDialog openFileDialog = new OpenFileDialog()) {
    ...
    }
  10. When coding C♯ classes and interfaces, the following formatting rules should be followed:
    • No space between a method name and the parenthesis "(" starting its parameter list.
    • The opening brace "{" appears in the next line after the declaration statement.
    • The closing brace " }" starts a line by itself indented to match its corresponding opening
    brace.
  11. Each line should contain only one statement.
  12. A return statement should not use outer most parentheses.
    Don't use : return (n * (n + 1) / 2);
    use : return n * (n + 1) / 2;
  13. if, if-else and if else-if else statements should look like this:
    if (condition) {
    DoSomething();
    ...
    }
    if (condition) {
    DoSomething();
    ...
    } else {
    DoSomethingOther();
    ...
    }
    if (condition) {
    DoSomething();
    ...
    } else if (condition) {
    DoSomethingOther();
    ...
    } else {
    DoSomethingOtherAgain();
    ...
    }
  14. A for statement shoud have following form :
    for (int i = 0; i < 5; ++i) {
    ...
    }
    or single lined (consider using a while statement instead) :
    for (initialization; condition; update) ;
    A foreach should look like :
    foreach (int i in IntList) {
    ...
    }
    Note: Generally use brackets even if there is only one statement in the loop.
  15. A while statement should be written as follows:
    while (condition) {
    ...
    }
    An empty while should have the following form:
    while (condition) ;
    A do-while statement should have the following form:
    do {
    ...
    } while (condition);
  16. A switch statement should be of following form:
    switch (condition) {
    case A:
    ...
    break;
    case B:
    ...
    break;
    default:
    ...
    break;
    }
  17. A try-catch statement should follow this form:
    try {
    ...
    } catch (Exception) {}
    or
    try {
    ...
    } catch (Exception e) {
    ...
    }
    or
    try {
    ...
    } catch (Exception e) {
    ...
    } finally {
    ...
    }
  18. Blank lines improve readability. They set off blocks of code which are in themselves logically related.
    Two blank lines should always be used between:
     Logical sections of a source file
     Class and interface definitions (try one class/interface per file to prevent this case)
    One blank line should always be used between:
     Methods
     Properties
     Local variables in a method and its first statement
     Logical sections inside a method to improve readability
    Note that blank lines must be indented as they would contain a statement this makes insertion in these lines
    much easier.
  19. There should be a single space after a comma or a semicolon, for example:
    TestMethod(a, b, c); don't use : TestMethod(a,b,c)
    or
    TestMethod( a, b, c );
  20. Single spaces surround operators (except unary operators like increment or logical not), example:
    a = b; // don't use a=b;
    for (int i = 0; i < 10; ++i) // don't use for (int i=0; i<10; ++i)
    // or
    // for(int i=0;i<10;++i)
  21. A logical block of lines should be formatted as a table:
    string name = "Mr. Ed";
    int myValue = 5;
    Test aTest = Test.TestYou;
    Use spaces for the table like formatting and not tabs because the table formatting may look strange in
    special tab intent levels.
  22. Pascal Casing
    This convention capitalizes the first character of each word (as in TestCounter).
  23. Camel Casing
    This convention capitalizes the first character of each word except the first one. E.g. testCounter.
  24. Only use all upper case for identifiers if it consists of an abbreviation which is one or two characters long,
    identifiers of three or more characters should use Pascal Casing instead. For Example:
    public class Math
    {
    public const PI = ...
    public const E = ...
    public const feigenBaumNumber = ...
    }
  25. Naming Guidelines
    Generally the use of underscore characters inside names and naming according to the guidelines for
    Hungarian notation are considered bad practice.
    Hungarian notation is a defined set of pre and postfixes which are applied to names to reflect the type of the
    variable. This style of naming was widely used in early Windows programming, but now is obsolete or at
    least should be considered deprecated. Using Hungarian notation is not allowed if you follow this guide.
    And remember: a good variable name describes the semantic not the type.
    An exception to this rule is GUI code. All fields and variable names that contain GUI elements like button
    should be postfixed with their type name without abbreviations. For example:
    System.Windows.Forms.Button cancelButton;
    System.Windows.Forms.TextBox nameTextBox;
  26. Class Naming Guidelines
     Class names must be nouns or noun phrases.
     UsePascal Casing see 8.1.1
     Do not use any class prefix
  27. Interface Naming Guidelines
     Name interfaces with nouns or noun phrases or adjectives describing behavior. (Example IComponent
    or IEnumberable)
     Use Pascal Casing (see 8.1.1)
     Use I as prefix for the name, it is followed by a capital letter (first char of the interface name)
  28. Enum Naming Guidelines
     Use Pascal Casing for enum value names and enum type names
     Don't prefix (or suffix) a enum type or enum values
     Use singular names for enums
     Use plural name for bit fields.
  29. ReadOnly and Const Field Names
     Name static fields with nouns, noun phrases or abbreviations for nouns
     Use Pascal Casing (see 8.1.1)
  30. Parameter/non const field Names
     Do use descriptive names, which should be enough to determine the variable meaning and it's type. But
    prefer a name that's based on the parameter's meaning.
     Use Camel Casing (see 8.1.2)
  31. Variable Names
     Counting variables are preferably called i, j, k, l, m, n when used in 'trivial' counting loops.
    (see 10.2 for an example on more intelligent naming for global counters etc.)
     Use Camel Casing (see 8.1.2)
  32. Method Names
     Name methods with verbs or verb phrases.
     Use Pascal Casing (see 8.1.2)
  33. Property Names
     Name properties using nouns or noun phrases
     Use Pascal Casing (see 8.1.2)
     Consider naming a property with the same name as it's type
  34. Event Names
     Name event handlers with the EventHandler suffix.
     Use two parameters named sender and e
     Use Pascal Casing (see 8.1.1 )
     Name event argument classes with the EventArgs suffix.
     Name event names that have a concept of pre and post using the present and past tense.
     Consider naming events using a verb.
  35. Capitalization summary
    Type Case Notes
    Class / Struct Pascal Casing
    Interface Pascal Casing Starts with I
    Enum values Pascal Casing
    Enum type Pascal Casing
    Events Pascal Casing
    Exception class Pascal Casing End with Exception
    public Fields Pascal Casing
    Methods Pascal Casing
    Namespace Pascal Casing
    Property Pascal Casing
    Protected/private Fields Camel Casing
    Parameters Camel Casing
  36. Visibility
    Do not make any instance or class variable public, make them private. For private members prefer not
    using "private" as modifier just do write nothing. Private is the default case and every C ♯ programmer
    should be aware of it.
    Use properties instead. You may use public static fields (or const) as an exception to this rule, but
    it should not be the rule.
  37. No 'magic' Numbers
    Don't use magic numbers, i.e. place constant numerical values directly into the source code. Replacing these
    later on in case of changes (say, your application can now handle 3540 users instead of the 427 hardcoded
    into your code in 50 lines scattered troughout your 25000 LOC) is error-prone and unproductive. Instead
    declare a const variable which contains the number :
    public class MyMath
    {
    public const double PI = 3.14159.. .
    }
  38. Brace placement example
    namespace ShowMeTheBracket
    {
    public enum Test {
    TestMe,
    TestYou
    }
    public class TestMeClass
    {
    Test test;
    public Test Test {
    get {
    return test;
    }
    set {
    test = value;
    }
    }
    void DoSomething()
    {
    if (test == Test.TestMe) {
    //...stuff gets done
    } else {
    //...other stuff gets done
    }
    }
    }
    }
    Brackets should begin on a new line only after:
    • Namespace declarations (note that this is new in version 0.3 and was different in 0.2)
    • Class/Interface/Struct declarations
    • Method declarations
  39. Variable naming example
    instead of :
    for (int i = 1; i < num; ++i) {
    meetsCriteria[i] = true;
    }
    for (int i = 2; i < num / 2; ++i) {
    int j = i + i;
    while (j <= num) {
    meetsCriteria[j] = false;
    j += i;
    }
    }
    for (int i = 0; i < num; ++i) {
    if (meetsCriteria[i]) {
    Console.WriteLine(i + " meets criteria");
    }
    }
    try intelligent naming :
    for (int primeCandidate = 1; primeCandidate < num; ++primeCandidate)
    {
    isPrime[primeCandidate] = true;
    }
    for (int factor = 2; factor < num / 2; ++factor) {
    int factorableNumber = factor + factor;
    while (factorableNumber <= num) {
    isPrime[factorableNumber] = false;
    factorableNumber += factor;
    }
    }
    for (int primeCandidate = 0; primeCandidate < num; ++primeCandidate)
    {
    if (isPrime[primeCandidate]) {
    Console.WriteLine(primeCandidate + " is prime.");
    }
    }
    Note: Indexer variables generally should be called i, j, k etc. But in cases like this, it
    may make sense to reconsider this rule. In general, when the same counters or indexers are
    reused, give them meaningful names.
  40. A


--
Happy day, happy life!

No comments: