Top Banner
DotNet Programming & Practices Dev Raj Gautam (Active Contributor ) AspNET Community 19th AspNetCommunity Meet-Up April 19th, 2014
23

DotNet programming & Practices

Jun 20, 2015

Download

Technology

Dev Raj Gautam

Best Practices To Follow In DotNet Programming
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: DotNet programming & Practices

DotNet Programming & Practices

Dev Raj Gautam

(Active Contributor )

AspNET Community

19th AspNetCommunity Meet-Up

April 19th, 2014

Page 2: DotNet programming & Practices

Naming Conventions

• Use Any naming conventions you like.• Prefix boolean variables, properties and methods with “is” or similar prefixes• Use PascalCasing for class names and method names, Use camelCasing for method arguments and local

variables is in Use.• Prefix boolean variables, properties and methods with “is” or similar prefixes• Identifier should tell what it does.• Prefix interfaces with the letter I.• Use appropriate prefix for each of the ui element

Example Of Naming Conventions public class HelloWorld { //using Pascal casing for Class and Methods void SayHello(string name) { //functionality for say hello } //Camel casing for variables and method parameters int totalCount = 0; void SayHello(string name) { string fullMessage = "Hello " + name; } }

Good:private bool _isIssuedint salaryIEntity lblAddress

Bad:int sal

Page 3: DotNet programming & Practices

Proper Documentation and Layout

• Write comments and documentation in US English

• Write XML documentation with another developer in mind

• Avoid inline comments

• Regions can be helpful, but can also hide the main purpose of a class. Therefore, use #regions only for:

Private fields and constants (preferably in a Private Definitions region). Nested classes Interface implementations (only if the interface is not the main purpose of that

class)

• Use proper indentation

Page 4: DotNet programming & Practices

Method Or Properties?

• If the work is more expensive than setting a field value.

• If it represents a conversion such as the Object.ToString method.

• If it returns a different result each time it is called, even if the arguments didn’t change. For example, the NewGuid method returns a different value each time it is called.

• If the operation causes a side effect such as changing some internal state not directly related the property

Page 5: DotNet programming & Practices

Concise and Unit Job Methods

Example of creating function that do only one job

SaveAddress ( address );

SendEmail ( address, email );

Private void SaveAddress ( string address )

{

// Save the address.

}

Private void SendEmail ( string address, string email )

{

// Send an email to inform that address is changed.

}

• A method should do only 'one job‘, don’t combine multiple jobs in single method.

• Don’t write large methods, normally 25 lines of the code is maximum to be included in one method.

• WHY?? Increases the maintainability

and reusability of the method Reduces the duplicity of code

Page 6: DotNet programming & Practices

Reduce the Number of Parameter

Excess parameters reduce method call performance. It is possible to optimize the parameters that a method receives. We remove unneeded parameters. This will reduce the memory usage on the stack and improve performance.

Example With Unused arguments static int Method1(int a, int b, int c, int d, int e, int f)

{

// This method contains extra parameters that are not used.

if (a == 0)

{

throw new Exception();

}

return a * 100 + b * 10 + c;

}

Example With arguments removed static int Method2(int a, int b, int c)

{

// This method only contains necessary parameters.

if (a == 0)

{

throw new Exception();

}

return a * 100 + b * 10 + c;

}

Page 7: DotNet programming & Practices

Keep Variables private and expose public/protected Properties

• If you share a member variable between methods, it will be difficult to track which method changed the value and when.

Page 8: DotNet programming & Practices

Properties, methods and arguments representing strings or collections should never be null

• Returning null can be unexpected by the caller. Always return an empty collection or an empty string instead of a null reference. This also prevents cluttering your code base with additional checks for null.

Page 9: DotNet programming & Practices

Should I always return IEnumerable<T> or ICollection<T>

• IF you don’t want callers to be able to change an internal collection, so don’t return arrays, lists or other collection classes directly. Instead, return an IEnumerable<T>, or, if the caller must be able to determine the count return an ICollection<T>

Page 10: DotNet programming & Practices

Favor Object and Collection Initializers over separate statements for Maintainability

What we Do?

var startInfo = new ProcessStartInfo(“myapp.exe”);

startInfo.StandardOutput = Console.Output;

startInfo.UseShellExecute = true;

var countries = new List<string>();

countries.Add(“Netherlands”);

countries.Add(“United States”);

Better

var startInfo = new ProcessStartInfo(“myapp.exe”)

{

StandardOutput = Console.Output,

UseShellExecute = true

};

var countries = new List<string> { “Netherlands”, “United States” };

Page 11: DotNet programming & Practices

Local Variable Field Optimization

Incase of frequent access copying the field to local variable is more efficient

No efficiency

class Program

{

static int _temp1; // Static field

static void Method1()

{

// Increment the static field ten times.

for (int i = 0; i < 10; i++)

{

_temp1++;

}

}

}

Efficientclass Program

{

static int _temp1; // Static field

static void Method2()

{

// Load static field into variable.

// ... Increment that ten times, then copy the value.

int copy = _temp1;

for (int i = 0; i < 10; i++)

{

copy++;

}

_temp1 = copy;

}

}

Page 12: DotNet programming & Practices

Avoid LINQ for simple expressions

Rather than

var query = from item in items where item.Length > 0;

prefer using the extension methods from the System.Linq namespace.

var query = items.Where(i => i.Length > 0);

Page 13: DotNet programming & Practices

Consider using Any() to determine whether an IEnumerable<T> is empty

• Use the Any() extension method rather than Count() to determine whether the collection contains items. If you do use Count(), you risk that iterating over the entire collection might have a significant impact.

Page 14: DotNet programming & Practices

Explicitly release object references?

• If the object is IDisposable it is a good idea to dispose of it when you no longer need it, especially if the object uses unmanaged resources. Not disposing of unmanaged resources will lead to memory leaks

Using Statement Exampleusing (MyIDisposableObject obj = new MyIDisposableObject()){ // use the object here}

Using Dispose()MyIDisposableObject obj;try{ obj = new MyIDisposableObject();}finally{ if (obj != null) { ((IDisposable)obj).Dispose(); }}

Page 15: DotNet programming & Practices

Switch Vs IF

Normally Switch Is faster than IF But If the input is almost always a specific value If preforms better

static bool IsValidIf(int i)

{

// Uses if-expressions to implement selection statement.

if (i == 0 || i == 1)

{

return true;

}

if (i == 2 ||i == 3)

{

return false;

}

if (i == 4 ||i == 5)

{

return true;

}

return false;

}

static bool IsValidSwitch(int i)

{

// Implements a selection statement with a switch.

switch (i)

{

case 0:

case 1:

return true;

case 2:

case 3:

return false;

case 4:

case 5:

return true;

default:

return false;

}

}

Page 16: DotNet programming & Practices

Be safe with 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

Bad

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.

}

BetterIf ( memberType == eMemberTypes.Registered )

{

// Registered user… do something…

}

else if ( memberType == eMemberTypes.Guest )

{

// Guest user... do something…

}

else

{

// Un expected user type. Throw an exception.

  // If we introduce a new user type in future, we can easily // find the problem here.

}

Page 17: DotNet programming & Practices

String Builder Class

Every time the string is concatenated a new string object Is created

public string ConcatString(string[] lines)

{

string LongString = String.Empty;

for (int i = 0; i < lines.Length; i++)

{

LongString += lines[i];

}

return LongString;

}

String builder is initialized once and on each concatenation it will get copied to memory

public string ConcatString(string[] lines)

{

StringBuilder LongString = new StringBuilder();

for (int i = 0; i < lines.Length; i++)

{

LongString.Append(lines[i]);

}

return LongString.ToString();

}

Page 18: DotNet programming & Practices

Use static Methods & Static fields

• Non-inlined instance methods are always slower than non-inlined static methods. To call an instance method, the instance reference must be resolved, to determine what method to call. Static methods do not use an instance reference.

• Why Static Methods are Fast?

The static methods can be invoked with fewer instructions

• Why Static Fields are Fast?

Loading an instance field must have the object instance first resolved. Even in an object instance, loading a static field is faster because no instance expression instruction is ever use

Page 19: DotNet programming & Practices

Exception Handling

• Never do a 'catch exception and do nothing‘

• Catch only the specific exception, not generic exception.

Example of catching specific Exceptionvoid ReadFromFile ( string fileName ) { try { // read from file. } catch (FileIOException ex) { // log error. // re-throw exception depending on your case. throw; } }

Page 20: DotNet programming & Practices

Exception Handling

• Don’t use large Try Catch Blocks, break the code into multiple try{} Catch{}, this will help to find which piece of code generated the exception and a specific exception message can be generated to user

• Always use the finally statement to close or deallocate resources

• Provide a rich and meaningful exception message text

Page 21: DotNet programming & Practices

Never Hard Code

• Don’t hardcode string or numbers

• Use constant if you are absolutely sure that the value will never be changed, config files and database are better place to store the values.

Page 22: DotNet programming & Practices

Build with the highest warning level

• Configure the development environment to use high Warning Level for the compiler, and enable the option Treat warnings as errors.

• This allows the compiler to enforce the highest possible code quality.

Page 23: DotNet programming & Practices

Thank You