C # Coding Specification 2

Source: Internet
Author: User

Coding Practices

  1. Avoid putting multiple classes in a single file.

  2. A single file shocould contrispontypes to only a single
    Namespace. Avoid having multiple namespaces in the same file.

  3. Avoid files with more than 500 lines (excluding
    Machine-generated code ).

  4. Avoid methods with more than 25 lines.

  5. Avoid methods with more than five arguments. Use structures
    Passing multiple arguments.

  6. Lines shoshould not exceed 80 characters.

  7. Do not manually edit any machine-generated code.

    1. If modifying machine-generated code, modify the format and
      Style to match this coding standard.

    2. Use partial classes whenever possible to factor out
      Maintained portions.

  8. Avoid comments that explain the obvious. Code shocould be
    Self-explanatory. Good code with readable variable and method names shocould not
    Require comments.

  9. Document only operational assumptions, algorithm insights, and
    So on.

  10. Avoid method-level documentation.

    1. Use extensive external documentation for API
      Documentation.

    2. Use method-level comments only as tool tips for other
      Developers.

  11. With the exception of zero and one, never hardcode a numeric
    Value; always declare a constant instead.

  12. UseConstDirective only on natural constants,
    Such as the number of days of the week.

  13. Avoid usingConstOn read-only variables. For that,
    UseReadonlyDirective:

    public class MyClass
    {
    public const int DaysInWeek = 7;
    public readonlyint Number;
    public MyClass(int someValue)
    {
    Number = someValue;
    }
    }

  14. Assert every assumption. On average, every has th line is
    Assertion:

    using System.Diagnostics;

    object GetObject( )
    {...}

    object someObject = GetObject( );
    Debug.Assert(someObject != null);

  15. Every line of code shocould be written ed through in a "white box"
    Testing manner.

  16. Catch only exceptions for which you have explicit
    Handling.

  17. InCatchStatement that throws an exception, always
    Throw the original exception (or another exception constructed from the original
    Exception) to maintain the stack location of the original error:

    catch(Exception exception)
    {
    MessageBox.Show(exception.Message);
    throw; //Same as throw exception;
    }

  18. Avoid error code as method return values.

  19. Avoid defining M exception classes.

  20. When defining custom exceptions:

    1. Derive the custom exception fromException.

    2. Provide custom serialization.

  21. Avoid MultipleMain ()Methods in a single
    Assembly.

  22. Make only the most necessary types public; mark others
    Internal.

  23. Avoid friend assemblies, as they increase interassembly
    Coupling.

  24. Avoid code that relies on an assembly running from a participant
    Location.

  25. Minimize code in application assemblies (I. e., exe Client
    Assemblies). Use class libraries instead to contain business logic.

  26. Avoid providing explicit values for enums:

    //Correct
    public enum Color
    {
    Red,Green,Blue
    }
    //Avoid
    public enum Color
    {
    Red = 1,Green = 2,Blue = 3
    }

  27. Avoid specifying a type for an Enum:

    //Avoid
    public enum Color : long
    {
    Red,Green,Blue
    }

  28. Always use a curly brace scope inIfStatement,
    Even if it contains a single statement.

  29. Avoid using the trinary conditional operator.

  30. Avoid function callin Boolean conditional statements. Assign
    Into local variables and check on them:

    bool IsEverythingOK( )
    {...}
    //Avoid:
    if(IsEverythingOK( ))
    {...}
    //Correct:
    bool ok = IsEverythingOK( );
    if(ok)
    {...}

  31. Always use zero-based arrays.

  32. Always explicitly Initialize an array of reference types:

    public class MyClass
    {}
    const int ArrraySize = 100;
    MyClass[] array = new MyClass[ArrraySize];
    for(int index = 0; index < array.Length; index++)
    {
    array[index] = new MyClass( );
    }

  33. Do not provide public or protected member variables. Use
    Properties instead.

  34. Avoid usingNewInheritance qualifier. Use
    OverrideInstead.

  35. Always Mark public and protected methodsVirtualIn
    A non-sealed class.

  36. Never use unsafe code, when T when using InterOP.

  37. Avoid explicit casting. UseAsOperator
    Defensively cast to a type:

    Dog dog = new GermanShepherd( );
    GermanShepherd shepherd = dog asGermanShepherd;
    if(shepherd != null)
    {...}

  38. Always check a delegateNullBefore invoking
    It.

  39. Do not provide public event member variables. Use event
    Accessors instead.

  40. Avoid defining event-handling delegates. Use
    GenericEventHandlerInstead.

  41. Avoid raising events explicitly. UseEventsHelperTo
    Publish events defensively.

  42. Always use interfaces.

  43. Classes and interfaces shocould have at least a ratio
    Methods to properties.

  44. Avoid interfaces with one member.

  45. Strive to have three to five members per interface.

  46. Do not have more than 20 members per interface. The practical
    Limit is probably 12.

  47. Avoid events as interface members.

  48. When using abstract classes, offer an interface
    Well.

  49. Expose interfaces on class hierarchies.

  50. Prefer using explicit interface implementation.

  51. Never assume a type supports an interface. Defensively query
    For that interface:

    SomeType obj1;
    IMyInterface obj2;

    /* Some code to initialize obj1, then: */
    obj2 = obj1 as IMyInterface;
    if(obj2 != null)
    {
    obj2.Method1( );
    }
    else
    {
    //Handle error in expected interface
    }

  52. Never hardcode strings that will be presented to end users. Use
    Resources instead.

  53. Never hardcode strings that might change based on deployment,
    Such as connection strings.

  54. UseString. EmptyInstead"":

    //Avoid
    string name = "";

    //Correct
    string name = String.Empty;

  55. When building a long string, useStringBuilder, Not
    String.

  56. Avoid providing methods on structures.

    1. Parameterized constructors are encouraged.

    2. You can overload operators.

  57. Always provide a static constructor when providing static
    Member variables.

  58. Do not use late-binding invocation when early binding is
    Possible.

  59. Use application logging and tracing.

  60. Never useGoto, Cannot t inSwitchStatement
    Fall-through.

  61. Always haveDefaultCase inSwitch
    Statement that asserts:

    int number = SomeMethod( );
    switch(number)
    {
    case 1:
    Trace.WriteLine("Case 1:");
    break;
    case 2:
    Trace.WriteLine("Case 2:");
    break;
    default:
    Debug.Assert(false);
    break;
    }

  62. Do not useThisReference unless invoking another
    Constructor from within a constructor:

    //Example of proper use of 'this'
    public class MyClass
    {
    public MyClass(string message)
    {}
    public MyClass( ) : this("Hello")
    {}
    }

  63. Do not useBaseWord to access base class members
    Unless you wish to resolve a conflict with a subclass member of the same name or
    When invoking a base class constructor:

    //Example of proper use of 'base'
    public class Dog
    {
    public Dog(string name)
    {}
    virtual public void Bark(int howLong)
    {}
    }
    public class GermanShepherd : Dog
    {
    public GermanShepherd(string name) : base(name)
    {}
    override public void Bark(int howLong)
    {
    base.Bark(howLong);
    }
    }

  64. Do not useGC. AddMemoryPressure ().

  65. Do not rely onHandleCollector.

  66. ImplementDispose ()AndFinalize ()Methods
    Based on the template in Chapter 4.

  67. Always run code unchecked by default (for the sake
    Performance), but explicitly in checked mode for overflow-or underflow-prone
    OPERATIONS:

    int CalcPower(int number,int power)
    {
    int result = 1;
    for(int count = 1;count <= power;count++)
    {
    checked
    {
    result *= number;
    }
    }
    return result;
    }

  68. Avoid explicit Code exclusion of method CILS
    (# If...# Endif). Use conditional methods instead:

    public class MyClass
    {
    [Conditional("MySpecialCondition")]
    public void MyMethod( )
    {}
    }

  69. Avoid casting to and fromSystem. ObjectIn code that
    Uses generics. Use constraints orAsOperator instead:

    class SomeClass
    {}
    //Avoid:
    class MyClass<T>
    {
    void SomeMethod(T t)
    {
    object temp = t;
    SomeClass obj = (SomeClass)temp;
    }
    }
    //Correct:
    class MyClass<T> where T : SomeClass
    {
    void SomeMethod(T t)
    {
    SomeClass obj = t;
    }
    }

  70. Do not define constraints in generic interfaces.
    Interface-level constraints can often be replaced by strong typing:

    public class Customer
    {...}
    //Avoid:
    public interface IList<T> where T : Customer
    {...}
    //Correct:
    public interface ICustomerList : IList<Customer>
    {...}

  71. Do not define method-specific constraints in
    Interfaces.

  72. If a class or a method offers both generic and non-generic
    Flavors, always prefer using the generics flavor.

  73. When implementing a generic interface that derived from
    Equivalent non-generic interface (suchIEnumerable <T>), Use
    Explicit interface implementation on all methods, and implement the non-generic
    Methods By delegating to the generic ones:

        class MyCollection<T> : IEnumerable<T>
    {
    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {...}
    IEnumerator IEnumerable.GetEnumerator()
    {
    IEnumerable<T> enumerable = this;
    return enumerable.GetEnumerator();
    }
    }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.