Mediaportal C# programming guidelines (1 Viewer)

Frodo

Retired Team Member
  • Premium Supporter
  • April 22, 2004
    1,518
    121
    51
    The Netherlands
    Home Country
    Netherlands Netherlands
    C# Sourcefiles
    Keep your classes/files short, don't exceed 2000 LOC, divide your code up, make structures clearer. Put every class in a separate file and name the file like the class name (with .cs as extension of course). This convention makes things much easier.

    Indentation
    Setup visual studio to use 2 spaces as identation

    Comments
    Block comments:
    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 :

    Single line comments:
    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.

    Single line comments must be indented to the indent level when they are used for code documentation. Commented out code should be commented out in the first line to enhance the visibility of commented out code.

    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.

    Documentation comments:
    In the .net framework, Microsoft has introduced a documentation generation system based on XML comments. These comments are formally single line C# comments containing XML tags. They follow this pattern for single line comments:
    Code:
    /// <summary>
    /// This class...
    /// </summary>
    Multiline XML comments follow this pattern:
    Code:
    /// <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

    The first category contains tags like <summary>, <param> or <exception>. These represent items that represent the elements of a program's API which must be documented for the program to be useful to other programmers. These tags usually have attributes such as name or cref as demonstrated in the multiline example above. These attributes are checked by the compiler, so they should be valid. The latter category governs the layout of the documentation, using tags such as <code>, <list> or <para>.
    Documentation can then be generated using the 'documentation' item in the #develop 'build' menu. The documentation generated is in HTMLHelp format.
    For a fuller explanation of XML comments see the Microsoft .net framework SDK documentation. For information on commenting best practice and further issues related to commenting, see the TechNote 'The fine Art of Commenting'.

    Declarations
    One declaration per line is recommended since it encourages commenting1. In other words,

    Code:
    int level; // indentation level
    int size; // size of table
    Do not put more than one variable or variables of different types on the same line when declaring them. Example:

    Code:
    int a, b; //What is 'a'? What does 'b' stand for?
    The above example also demonstrates the drawbacks of non-obvious variable names. Be clear when naming variables.

    Class and Interface Declarations
    #

    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.

    For example:

    Code:
    Class MySample : MyClass, IMyInterface
    {
    	int myInt;
    	public MySample(int myInt)
    	{
    	  this.myInt = myInt ;
    	}
    	void Inc()
    	{
    	  ++myInt;
    	}
    	void EmptyMethod()
    	{
    	}
    }
    For a brace placement example look at section 10.1.

    If, if-else, if else-if else Statements

    Code:
    if (condition) 
    {
      DoSomething();
      ...
    }
    if (condition) 
    {
      DoSomething();
      ...
    } 
    else 
    {
      DoSomethingOther();
      ...
    }
    if (condition) 
    {
      DoSomething();
      ...
    } 
    else if (condition) 
    {
      DoSomethingOther();
      ...
    } 
    else 
    {
      DoSomethingOtherAgain();
      ...
    }

    For / Foreach Statements
    A for statement shoud have following form :

    Code:
    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 :
    Code:
      foreach (int i in IntList) 
      {
         ...
      }

    While/do-while Statements
    A while statement should be written as follows:

    Code:
    while (condition) 
    {
      ...
    }

    An empty while should have the following form:

    Code:
    while (condition) ;
    A do-while statement should have the following form:

    Code:
    do 
    {
      ...
    } while (condition);

    Switch Statements
    Code:
    switch (condition) 
    {
      case A:
      ...
      break;
      case B:
      ...
      break;
      default:
      ...
      break;
    }

    Try-catch Statements
    A try-catch statement should follow this form:

    Code:
    try 
    {
      ...
    } catch (Exception) 
    {
      ...
    }
    finally
    {
    }

    White space
    #
    Blank Lines

    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.

    Inter-term spacing
    There should be a single space after a comma or a semicolon, for example:

    Code:
    TestMethod(a, b, c); don't use : TestMethod(a,b,c)

    Code:
    TestMethod( a, b, c );
    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)


    Table like formatting

    A logical block of lines should be formatted as a table:

    Code:
    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.


    Naming Conventions
    Capitalization Styles

    Pascal Casing

    This convention capitalizes the first character of each word (as in TestCounter).

    Camel Casing

    This convention capitalizes the first character of each word except the first one. E.g. testCounter.

    Upper case

    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:

    Code:
    public class Math
    {
      public const PI = ...
      public const E = ...
      public const feigenBaumNumber = ...
    }

    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:

    Code:
    System.Windows.Forms.Button cancelButton;
    System.Windows.Forms.TextBox nameTextBox;

    Class Naming Guidelines
    # Class names must be nouns or noun phrases.
    # UsePascal Casing
    # Do not use any class prefix


    Interface Naming Guidelines
    # Name interfaces with nouns or noun phrases or adjectives describing behavior. (Example IComponent or IEnumberable)
    # Use Pascal Casing
    # Use I as prefix for the name, it is followed by a capital letter (first char of the interface name)

    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.



    ReadOnly and Const Field Names
    # Name static fields with nouns, noun phrases or abbreviations for nouns
    # Use Pascal Casing

    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

    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

    Method Names
    # Name methods with verbs or verb phrases.
    # Use Pascal Casing

    Property Names
    # Name properties using nouns or noun phrases
    # Use Pascal Casing
    # Consider naming a property with the same name as it’s type

    Event Names
    # Name event handlers with the EventHandler suffix.
    # Use two parameters named sender and e
    # Use Pascal Casing
    # 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.



    Code:
    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 Fields		Camel Casing	 
    private Fields			Camel Casing	 
    Parameters				Camel Casing
     

    Frodo

    Retired Team Member
  • Premium Supporter
  • April 22, 2004
    1,518
    121
    51
    The Netherlands
    Home Country
    Netherlands Netherlands
    Part II

    Programming Practices
    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.
    9.2 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 :

    Code:
    public class MyMath
    {
      public const double PI = 3.14159...
    }

    Brace code example
    Code:
    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
    			}
    		}
    	}
    }

    Variable naming example

    Code:
    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.");
    	}
    }
     

    Mars Warrior

    Portal Pro
    August 26, 2004
    158
    2
    Airy Crater, Mars
    Home Country
    Nice Frodo ;)

    Is this only meant for new code, or is it your intention to let the full MP codebase adhere to these standards :twisted: :twisted:

    Ever thought of using FxCop to analyse the code to see if it is compliant with the C# coding and naming conventions?? It could save a lot of work analysing the code by hand...


    FxCop Team Page

    Its a very nice utility, it found about 11.000 issues while analyzing MP :shock: :shock:

    =====
    About FxCop
    FxCop is a code analysis tool that checks .NET managed code assemblies for conformance to the Microsoft .NET Framework Design Guidelines. It uses reflection, MSIL parsing, and callgraph analysis to inspect assemblies for more than 200 defects in the following areas:

    - Library design
    - Localization
    - Naming conventions
    - Performance
    - Security

    FxCop includes both GUI and command line versions of the tool, as well as an SDK to create custom rules.
    ===
     

    Frodo

    Retired Team Member
  • Premium Supporter
  • April 22, 2004
    1,518
    121
    51
    The Netherlands
    Home Country
    Netherlands Netherlands
    so this only meant for new code, or is it your intention to let the full MP codebase adhere to these standards Twisted Evil Twisted Evil
    this is for new & changed code.
    I know the existing code doesnt follow all these rules yet, but its to much work to rewrite everything.d So for now, only the new & changed code
    frodo
     

    LastMar

    Portal Pro
    November 17, 2004
    74
    0
    I noticed.

    I was gonna tinker with the code a bit, until i saw the (lack of) commenting.... It's probably for the best since I don't know C# anyway. I only know C++, and I'm not even very good at that...
     

    Frodo

    Retired Team Member
  • Premium Supporter
  • April 22, 2004
    1,518
    121
    51
    The Netherlands
    Home Country
    Netherlands Netherlands
    don't worry
    we'll add comments the next few months to get the code more understandable. The most difficult code is already commented
    (guilib & my tv)
    frodo
     

    waeberd

    Portal Pro
    August 16, 2004
    314
    1
    Fribourg (CH)
    thanks frodo, nice guidelines!

    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

    damned.... I feel very, very old!!! :?
     

    koniosis

    Portal Member
    January 21, 2005
    7
    0
    Hey guys, new here, been checking out the project. Was looking at this section because I am planning on helping out, I've been working with Managed DirectX for 1.5 years and C# for 4, so hopefully I can add something useful. Anyway I thought I'd give you my 2c on some styles which I've found to be very useful when coding.

    The first style is with regard to /// xml comments; if you look at Microsoft C# code (the Managed DirectX samples are a good example), they often "in-line" their summaries on variables and I've found this makes things a hell of a lot more readable, since you can view at least three times as many variables per page and your code isn't littered with /// lines. E.g

    Code:
    ///<summary>This is the music playlist</summary>
    ArrayList MusicPlaylist = new PlayList();
    
    ///<summary>This is the movie playlist</summary>
    ArrayList MoviePlaylist = new PlayList();
    
    // as opposed to:
    
    ///<summary>
    ///This is the music playlist
    ///</summary>
    ArrayList MusicPlaylist = new PlayList();
    
    ...

    Although you're probably going to cringe at first (as I did) it just works so well for short comments, so much so that the Whidbey team have said in Orcas they're going to make it an option to have xml comments in this style. Also works well for methods, in fact it's generally much tidier when you're only using single-line summaries. I still suggest multi-line summaries get the full works.

    Second thing to get the "inline" treatment is Properties. Again, it seems so wrong to mix inline and line broken code, but once again it just works so well. Example:

    Code:
    public class SomeClass
    {
      private int m_Playlist;
    
      public int Playlist { get { return m_Playlist; } set { m_Playlist = value; } }
    }

    Now obviously if you're going to have more than just a standard assignments inside your Properties it makes more sense for you to use multi-line; but for something so simple the inline approach is very readable and looks tidy. I haven't come across any other situations where inline code is better, just with Properties since they are so predictable (i.e. return x; x = value)

    Of course, I'm just passing on some useful styles that I've encountered during my time coding C#; which I've also seen implimented by others (e.g. MDX team). I don't mean to come barging in with like "HEY DO IT MY WAY!!". But I do recommend you try converting a class with a lot of Properties and XML comments into these styles and see how you feel about it. Like I said, I was sceptical at first.

    With best intentions,

    Koni
     
    V

    Vic

    Guest
    I agree with Bionicdonkey...I also find it easier to read 4 space indented code. It is also the default setting in Visual Studio. Why change it?

    I have also noticed that most of the files in MediaPortal are not properly tabified, but filled with spaces. I.e. spaces are used to indent the code - not tabs! This is really ugly. If the code was properly tabified I think everyone could use their own preferred setting for the tab indentation and it would work anyway. Right now the code looks terrible when 4 space indendation is used.

    P.S - Visual Studio can tabify code easily. Just hit CTRL+A to select all and then go to Edit->Advanced->Tabify Selection.
     

    Users who are viewing this thread

    Top Bottom