Some Useful Tips For Clean Coding

First of all coding is a art…There are some rule to follow ..

1.Naming of Variable and method name.

Variable name should be clear and concise .
Function name should be also be clear.

Most important part is to be clear naming of global and local variable.

2.Coding style of Languaage
Golbal Getter/Setter–Pascal
variable–Cammel Case
Global variable–_(followed By Underscore)

3.Put comment for explanation not for garbage code.Garbage code will be available n Git .So no need to worry :).

5.Do not hard code Never assign a const variable in local function .Hard coding is hard to find for a developer .

6.Never use of too much variable.Use less variable as possible and precise.

7.function should have <=three parameter..less is merrier 8.Do not use var if you are not getting correct type. var customer=new Coustomer(); //Good but var customer=SomeFunctionWithParam(); //Not good Because that will not give correct expression name 9.Be positive .But i am not ... A Boolean variable is always positive.Because negativity is often hard to find bacause of double negative . 9.This link is perfect for some beginner

and also general coding best practices

Avoid stateful object
A stateful object is an object that contains many properties and lots of behavior behind that. If you expose such an object through a static property or method of some other object, it will be very difficult to refactor or unit test a class that relies on such a stateful object.
A classic example of this is the HttpContext.Current property, part of ASP.NET. Many see the HttpContext class as a source for a lot of ugly code. In fact, the testing guideline Isolate the Ugly Stuff often refers to this class.
Return an IEnumerable or ICollection instead of a concrete collection class
In general, 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, or, if the caller must be able to determine the count, an
Note If you’re using .NET 4.5, you can also use IReadOnlyCollection, IReadOnlyList or IReadOnlyDictionary
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, or even worse, string.IsNotNullOrEmpty().
Define parameters as specific as possible
If your member needs a specific piece of data, define parameters as specific as that and don’t take a container object instead. For instance, consider a method that needs a connection string that is exposed through some central IConfiguration interface. Rather than taking a dependency on the entire configuration, just define a parameter for the connection string. This not only prevents unnecessary coupling, it also improved maintainability in the long run.

Evaluate the result of a LINQ expression before returning it
Consider the following code snippet

public IEnumerable GetGoldMemberCustomers()
const decimal GoldMemberThresholdInEuro = 1000000;

var q = from customer in db.Customers

where customer.Balance > GoldMemberThresholdInEuro select new GoldMember(customer.Name, customer.Balance);

return q;


Since LINQ queries use deferred execution, returning q will actually return the expression tree representing the above query. Each time the caller evaluates this result using a foreach or something similar, the entire query is re-executed resulting in new instances of GoldMember every time. Consequently, you cannot use the == operator to compare multiple GoldMember instances. Instead, always explicitly evaluate the result of a LINQ query using ToList(), ToArray() or similar methods.

Avoid conditions with double negatives
Although a property like customer.HasNoOrders make sense, avoid using it in a negative condition like this:
bool hasOrders = !customer.HasNoOrders;
Double negatives are more difficult to grasp than simple expressions, and people tend to read over the double negative easily.
Methods should not exceed 7 statements
A method that requires more than 7 statements is simply doing too much or has too many responsibilities. It also requires the human mind to analyze the exact statements to understand what the code is doing. Break it down in multiple small and focused methods with self-explaining names, but make sure the high-level algorithm is still clear.
Don’t use literal values, either numeric or strings, in your code other than to define symbolic constants. For example:
public class Whatever {
public static readonly Color PapayaWhip = new Color(0xFFEFD5);
public const int MaxNumberOfWheels = 18;
Strings intended for logging or tracing are exempt from this rule. Literals are allowed when their meaning is clear from the context, and not subject to future changes, For example:
mean = (a + b) / 2; // okay
WaitMilliseconds(waitTimeInSeconds * 1000); // clear enough
If the value of one constant depends on the value of another, do attempt to make this explicit in the code.
public class SomeSpecialContainer
public const int MaxItems = 32;
public const int HighWaterMark = 3 * MaxItems / 4; // at 75%
Pure functions dont change state of an object
Don’t use “magic” numbers

Don’t use literal values, either numeric or strings, in your code other than to define symbolic constants. For example:

public class Whatever
public static readonly Color PapayaWhip = new Color(0xFFEFD5); public const int MaxNumberOfWheels = 18;

Only use var when the type is very obvious
Only use var as the result of a LINQ query, or if the type is very obvious from the same statement and using it would improve readability. So don’t.

Instead, use var like this.

var q = from order in orders where order.Items > 10 and order.TotalValue > 1000;
var repository = new RepositoryFactory.Get();

var list = new ReadOnlyCollection();

In all of three above examples it is clear what type to expect. For a more detailed rationale about the advantages and disadvantages of using var, read Eric Lippert’s Uses and misuses of implicit typing.

Declare and initialize variables as late as possible

Avoid the C and Visual Basic styles where all variables have to be defined at the beginning of a block, but rather define and initialize each variable at the point where it is needed.

Assign each variable in a separate statement
Don’t use confusing constructs like the one below.
var result = someField = GetSomeMethod();

Favor Object and Collection Initializers over separate statements
Instead of

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

startInfo.StandardOutput = Console.Output; startInfo.UseShellExecute = true;

Use Object Initializers

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

StandardOutput = Console.Output, UseShellExecute = true

Similarly, instead of

var countries = new List();
countries.Add(“United States”);

Use collection or dictionary initializers

var countries = new List
“United States”

**Don’t make explicit comparisons to true or false

It is usually bad style to compare a bool-type expression to true or false. For example:

while (condition == false) // wrong; bad style
while (condition != true) // also wrong
While (((condition == true) == true) == true) // where do you stop?
while (condition) // OK

Don’t change a loop variable inside a for or foreach loop

Updating the loop variable within the loop body is generally considered confusing, even more so if the loop variable is modified in more than one place. Although this rule also applies to foreach loops, an enumerator will typically detect changes to the collection the foreach loop is iteration over.

for (int index = 0; index < 10; ++index) { if (some condition) { index = 11; // Wrong! Use ‘break’ or ‘continue’ instead. } } **Avoid nested loops A method that nests loops is more difficult to understand than one with only a single loop. In fact, in most cases having nested loops can be replaced with a much simpler LINQ query that uses the from keyword twice or more to join the data. Always add a block after keywords such if, else, while, for, foreach and case Please note that this also avoids possible confusion in statements of the form: if (b1) if (b2) Foo(); else Bar(); // which ‘if’ goes with the ‘else’? // The right way: if (b1) { if (b2) { Foo(); } else { Bar(); } } Always add a default block after the last case in a switch statement Add a descriptive comment if the default block is supposed to be empty. Moreover, if that block is not supposed to be reached throw an InvalidOperationException to detect future changes that may fall through the existing cases. This ensures better code, because all paths the code can travel has been thought about. void Foo(string answer) { switch (answer) { case "no": Console.WriteLine("You answered with No"); break; case "yes": Console.WriteLine("You answered with Yes"); break; default: // Not supposed to end up here. throw new InvalidOperationException("Unexpected answer " + answer); } } Finish every if-else-if statement with an else-part For example void Foo(string answer) { if (answer == "no") { Console.WriteLine("You answered with No"); } else if (answer == "yes") { Console.WriteLine("You answered with Yes"); } else { // What should happen when this point is reached? Ignored? If not, // throw an InvalidOperationException. } } if (val > 0)
pos = true;
pos = false;


bool pos = (val > 0); // initialization

Or instead of

string result;

if (someString != null)
result = someString;
result = “Unavailable”;

return result;


return someString ?? “Unavailable”;

Don’t allow methods and constructors with more than three parameters
If you end up with a method with more than three parameters, use a structure or class for passing multiple arguments such as explained in the Specification design pattern. In general, the fewer the number of parameters, the easier it is to understand the method. Additionally, unit testing a method with many parameters requires many scenarios to test.

Don’t use ref or out parameters
They make code less understandable and might cause people to introduce bugs. Prefer returning compound objects instead.

Avoid methods that take a bool flag
Consider the following method signature:
public Customer CreateCustomer(bool platinumLevel) {}

On first sight this signature seems perfectly fine, but when calling this method you will lose this purpose completely:
Customer customer = CreateCustomer(true);
Often, a method taking such a flag is doing more than one thing and needs to be refactored into two or more methods. An alternative solution is to replace the flag with an enumeration.

Don’t use parameters as temporary variables
Never use a parameter as a convenient variable for storing temporary state. Even though the type of your temporary variable may be the same, the name usually does not reflect the purpose of the temporary variable.

Always check the result of an as operation
If you use as to obtain a certain interface reference from an object, always ensure that this operation does not return null. Failure to do so may cause a NullReferenceException at a much later stage if the object did not implement that interface.

Don’t comment out code

Never check-in code that is commented-out, but instead use a work item tracking system to keep track of some work to be done. Nobody knows what to do when they encounter a block of commented-out code. Was it temporarily disabled for testing purposes? Was it copied as an example? Should I delete it?

Use US-English
All type members, parameters and variables should be named using words from the American English language.

• Choose easily readable, preferably grammatically correct names. For example, HorizontalAlignment is more readable than AlignmentHorizontal.

• Favor readability over brevity. The property name CanScrollHorizontally is better than ScrollableX (an obscure reference to the X-axis).

• Avoid using names that conflict with keywords of widely used programming languages.

Exception In most projects, you will use words and phrases from your domain and names specific to your company.

Avoid short names or names that can be mistaken with other names
Although technically correct, the following statement can be quite confusing.
bool b001 = (lo == l0) ? (I1 == 11) : (lOl != 101);
Properly name properties
 Do name properties with nouns, noun phrases, or occasionally adjective phrases.
 Do name Boolean properties with an affirmative phrase. E.g. CanSeek instead of CantSeek.
 Consider prefixing Boolean properties with Is, Has, Can, Allows, or Supports.

 Consider giving a property the same name as its type. When you have a property that is strongly typed to an enumeration, the name of the property can be the same as the name of the enumeration. For example, if you have an enumeration named CacheLevel, a property that returns one of its values can also be named CacheLevel.

Name methods using verb-object pair
Name methods using a verb-object pair such as ShowDialog. A good name should give a hint on the what of a member, and if possible, the why. Also, don’t include and in the name of the method. It implies that the method is doing more than one thing, which violates the single responsibility principle.

Performance Guidelines

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

When a method or other member returns an IEnumerable or other collection class that does not expose a Count property, 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 (such as when it really is an IQueryable to a persistent store).

Only use async for low-intensive long-running activities
The usage of async won’t automagically run something on a worker thread like Task.Run does. It just adds the necessary logic to allow releasing the current thread and marshal the result back on that same thread if a long-running asynchronies operation has completed. In other words, use async only for I/O bound operations.

Prefer Task.Run for CPU intensive activities
If you do need to execute a CPU bound operation, use Task.Run to offload the work to a thread from the Thread Pool.
Just don’t forget that you have to marshal the result back to your main thread manually.
Beware of mixing up await/async with Task.Wait
await will not block the current thread but simply instruct to compiler to generate a state-machine. However, Task.Wait will block the thread and may even cause dead-locks.

Beware of async/await deadlocks in single-threaded environments
Consider the following asynchronous method:
private async Task GetDataAsync()
var result = await MyWebService.GetDataAsync(); return result.ToString();

Now when an ASP.NET MVC controller action does this:
public ActionResult ActionAsync()
var data = GetDataAsync().Result;

return View(data);

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);
Since LINQ queries should be written out over multiple lines for readability, the second example is a bit more readable.
Use Lambda expressions instead of delegates
Lambda expressions provide a much more elegant alternative for anonymous delegates. So instead of
Customer c = Array.Find(customers, delegate(Customer c)

return c.Name == “Tom”;


use a Lambda expression:
Customer c = Array.Find(customers, c => c.Name == “Tom”);

Or even better
var customer = customers.Where(c => c.Name == “Tom”);

Only use the dynamic keyword when talking to a dynamic object

The dynamic keyword has been introduced for working with dynamic languages. Using it introduces a serious performance bottleneck because the compiler has to generate some complex Reflection code.

Use it only for calling methods or members of a dynamically created instance (using the Activator) class as an alternative to Type.GetProperty() and Type.GetMethod(), or for working with COM Interop types.

Favor async/await over the Task

Using the new C# 5.0 keywords results in code that can still be read sequentially and also improves maintainability a lot, even if you need to chain multiple asynchronous operations. For example, rather than defining your method like this:

public Task GetDataAsync()
return MyWebService.FetchDataAsync()
.ContinueWith(t => new Data (t.Result));

define it like this:

public async Task GetDataAsync()
var result = await MyWebService.FetchDataAsync();

return new Data (result);

Consider the following method in C# CODE REFACTORING AND GOOD PRACTISES

public string transform(List s)
string d = null;
foreach (DateTime kc in s)
{if (kc > DateTime.Now)
{ d = d + kc + “\n”; }
else { d = d + “Delayed\n”; }}

After reformatting

public string GetText(List arrivalTimes)
var stringBuilder = new StringBuilder();
foreach (DateTime arrivalTime in arrivalTimes)
if (arrivalTime > DateTime.Now)
return stringBuilder.ToString();

Or if we apply the “?:” operator, we will get:
public string GetText(List arrivalTimes)
var stringBuilder = new StringBuilder();
foreach (DateTime arrivalTime in arrivalTimes)
string message = arrivalTime > DateTime.Now ? arrivalTime.ToString() : “Delayed”;
return stringBuilder.ToString();

What has actually happened to the code? Several modifications have been made to increase its readability:
1. The name of the method has been changed from one that really doesn’t say anything to one that is a little bit more descriptive.
2. The way of naming the variables was changed:
1. “kc” was changed to arrivalTime,
2. “s” was changed to arrivalTimes,
3. “d” was changed to stringBuilder,
It also much easier to understand what each variable is responsible for and how it was used.
1) Parentheses have been standardized to one format.
2) Tabs have been added to increase readability, spacing, and nesting in braces.
3) The “?:” operator has been used to reduce the length of the code by 4 lines.
4) The StringBuilder class was added to avoid string concatenation (“string” + “string”). Although some may argue that creating the StringBuilder instance will slow down the method due to its memory allocation, I would like to remind everyone that string concatenation creates a lot of allocation for Garbage Collector to clean up. It is considered that ~5 string concasts are equal to creating instances of StringBuilder, so if a list consists of 5 or more elements the performance of this method will actually increase. And for larger collections this method will work several times faster.
Let us go through another example. Consider User class (just for demonstration purposes):
public class User
public bool HasConfirmedEmail { get; set; }
public bool HasActiveAccount { get; set; }
public bool IsLoggedIn { get; set; }
public bool HasPremiumAccount { get; set; }
public bool StatusAutoGenerated { get; set; }
public DateTime LastStatusChange { get; set; }

public bool SetStatus(string status)
// write to Data Base
return true;

And a method that is responsible for updating user status that has to check if all properties are in correct state:

public string UpdateStatus(string status, User user)
if (user.HasActiveAccount)
if (user.HasConfirmedEmail)
if (user.IsLoggedIn)
if (user.HasPremiumAccount)
if (!user.StatusAutoGenerated)
if (user.LastStatusChange < DateTime.Now.AddDays(-1)) { if (user.SetStatus(status)) { return "Updated"; } } } } } } } return "Fail"; } Correction: const string OK = "Updated"; const string FAIL = "Fail"; public string UpdateStatus(string status, User user) { if (!CanUpdateStatus(user)) return FAIL; if (!user.SetStatus(status)) return FAIL; return OK; } public static bool CanUpdateStatus(User user) { if (!user.IsLoggedIn) return false; if (!user.HasActiveAccount) return false; if (!user.HasConfirmedEmail) return false; if (!user.HasPremiumAccount) return false; if (user.StatusAutoGenerated) return false; if (!(user.LastStatusChange < DateTime.Now.AddDays(-1))) return false; return true; } The main modifications that have been made to this code to increase its readability and maintainability: 1. A static method has been created to check if the user status can be updated. This makes the UpdateStatus method way simpler to understand at first glance. Also, the CanUpdateStatus method logic can now be reused in other parts of the system as it is public and static. 2. All the “if” statements have been reversed to reduce nesting. Now almost all of parentheses are gone and it is much easier to read or debug through the code. Another advantage of this convention is its scalability. Imagine that the User class has now three more properties that need to be checked before updating status – 3 more “if” statement nestings would be necessary. Now you can only add three more lines in the CanUpdatedStatus method. 3. Strings that represent messages were removed from bodies of the methods and were put in constant variables. This also helps with maintaining the code because regardless of the number of usages of the code there is only one place where you have to change the content of the message if needed. To be honest though, all the texts should be transferred to an external resources project.

Leave a Reply

Your email address will not be published. Required fields are marked *