Powered By Blogger

Wednesday, October 5, 2022

Coding Standards

 C#:

1. Naming Conventions:

    a) Pascal Case: Use this style when naming a class, record, or structs. The interface also uses this convention with the prefix of ‘I’. Public members such as fields, properties, events, methods, and local functions also use pascal case.

    b) Camel Case: Use this style for method parameters and when naming private or internal fields prefix with ‘_’. If the private or internal field is static us the prefix ‘s_’ instead. If the private or internal field is static thread us the prefix ‘t_’ instead.


2) Layout Convention:

     The layout convention is meant to have the code structure in a specific way. Follow these guidelines:

• 4 spaces or a tab is used for indentations

• 1 statement per line

• 1 declaration per line

• Continuation lines require indentations

• 1 empty line between method definitions and property definitions

• Use parentheses to make clauses in an expression apparent

• Region can be used to group separate sections

• Break multiple conditions in an if-statement into several lines instead of one long line

Tip: If you have to scroll in either direction and you remain in the same function or method, it needs to be refactored and broken into smaller parts.


3) Commenting Convention:

    Adding comments to the code should provide insights into parts that are not self-explanatory or has a very specific intention not obvious to the reader. Some guidelines to follow for creating comments:

• Comment on a separate line, not in-line

• Begin with a capital letter

• End with a period (.)

• Have a space between the // and the comment

• Don’t created blocks around the comment

All public members require the necessary XML comments and headers, it is also suggested for the rest of the members.


4) Language Guidelines:

    String

Use the appropriate string concatenation functions, don’t use ‘+’:

var firstname = $"My name is {user.FirstName}";

Use the StringBuilder class when you need to append strings in a loop or working with large amounts of string.

Var (Implicitly typed)

Use the ‘var’ for local variables when the right-hand side assignment is clear and obvious, or when implicit typing in a loop is used (for-loop).

Don’t use ‘var’ when:

• The assignment is not clear

• The assignment relies on a function

• You can use dynamic for run-time inference

• In a foreach-loop

• You can use the ‘let’ keyword for scope limiting

Note: The keyword ‘var’ needs to be taken up with the programmer on their usage and understanding thereof. Consistency is more important.


5) Array:

    This section will provide some notes around the initialization of an array object. When working with arrays, use the concise syntax:

string[] vowels = {"a", "e", "i", "o", "u"};

If you need to specify the array size, or you need to instantiate it, user ‘var’:

var vowels1 = new string[] {"a", "e", "i", "o", "u"};

var vowels2 = new string[5];


6) Delegates:

    Use Func<> or Action<> instead of delegate types. Keep to the concise syntax where possible:

    public static Action<string> ActionExample1 = x => Console.WriteLine($"x is: {x}");

    public static Func<int, int, int> FuncExample2 = (x,y) => x + y;


   class DelClass{

        public delegate void Del(string message);

        public static void DelMethod(string str){

       Console.WriteLine("DelMethod argument: {0}", str);

            }

       }


7) Try-Catch and Using:

    The try-catch is used for most of the exception handling. Use the using-statement instead of a try-finally. The using statement can also be used in a shorth-hand version:

using Font font3 = new Font("Arial", 10.0f);

byte charset3 = font3.GdiCharSet;


8) && and ||:

   Use the double ampersand (&&) or double pipe character (||) instead of the singles.

9) New:

    var instance1 = new ExampleClass();

    ExampleClass instance2 = new();

Use the initializers of a class before using the properties:

    var instance3 = new ExampleClass { Name = "Desktop", ID = 37414, Location = "Redmomd", Age = 2.3 };


10) Event Handling:

      Use the lambda expression when defining an event handler that is permanent:

public Form2()

{

  this.Click += (s,e) =>

     {

         MessageBox.Show(

           ((MouseEventArgs)e).Location.ToString());

     };

}


      Else, use the full notation:

public Form1()

{

  this.Click += new EventHandler(Form1_Click);

}

void Form1_Click(object? sender, EventArgs e)

{

  MessageBox.Show((MouseEventArgs)e).Location.ToString());

}


11) Static Members

Call all the static members by using the class name dot member (ClassName.StaticMethod). Don’t use a derived class name.

12) LINQ

Follow the guidelines on LINQ expressions:

• Use descriptive names for the variables

• Use Pascal casing

• Rename any ambiguous properties that are returned

• Use implicit typing in the declaration

• Use the where-clause before other clauses

• Use multiple from-clauses instead of a join


13) Other Notes

Here are some guidelines on programming in general.

Rule of thumb:

• A function has maximum 50 lines of code

• A class has maximum of 700 lines of code

• Add a space between operators

• Opening and closing parenthesis are present with keywords

• Function and method names should be meaningful

• A function or method has a single responsibility

• Do not hardcode string or number (use a separate file)

• String comparisons are in upper- or lower case

• Use enums instead of strings or numbers where applicable

• Use constants for the logger

• Log messages should be of value

• Maximum number of parameters is 5

• Use a class or structure for more parameters

• Collections should be empty, not null

• Use Any() instead of Count()

• Use foreach instead of for-loop

• Use interfaces instead of concrete classes for collections

• Files and connections should be closed in a finally-statement

• Catch specific exceptions only, not generic ones

• Be careful of swallowing exceptions

No comments:

Post a Comment

Tools for Unit Testing in Power Platform