Vivasoft-logo
[rank_math_breadcrumb]

10 Coding Best Practices and Tips by Vivasoft Developers to Follow

10 Coding Best Practices and Tips by Vivasoft Developers

Writing clean code offers better performance and faster development. Sometimes “quick and dirty” code may save time during development but there is a strong likelihood it will cost you time later fixing the bugs. Writing clean code is a matter of habit which is easier to maintain and easier to spot bugs in a long run. Here some tips have been described on how we can write more readable and cleaner code and some new features we can adopt.

1. Keep your functions/method simple

Avoid writing long functions. The simpler your class is, your code is more readable and cleaner. If any function is required to write a hundred lines of business logic, break it down into smaller functions and name it appropriately describing the steps best way.

2. Pay attention to readability and meaningful method/property name

  • Use variable names that are easy to remember
    • Bad Practice
    • Good Practice
  • Use searchable names
    • Bad Practice
    • Good Practice
  • Use camel case notation for local variables and arguments
    • Bad Practice
    • int RandomInteger;string FirstName;

    • Good Practice
    • int randomInteger;string firstName;

  • Add comments whenever necessary and only when the situation demands. For example, when a particular method is too complex and requires an in-depth explanation. Maintaining comments will become a task as well. So use comments wisely.

3. Don’t repeat yourself

This error is very common because we unconsciously repeat names or words. This bad practice in the long run makes you have a very dirty code since there will be many things that will be repeated. Let’s get down to practice:

Bad practice

Good practice

4. Follow the ‘early return’ principle

Return early is the way of writing functions or methods so that the invalid cases validate first and return as early as possible. The expected positive result is returned at the end of the function after some required validations. It works as a guard of the functions for invalid cases.

5. Simple way of using the If/else statement

We often write a validation case that has to return a bool value from a function:

Although this approach is mostly fine, we have to ask ourselves if we even need an if-statement in the first place. Since we already have a logical expression inside the if-statement, we can simplify the method by simply returning the value of that logical expression:

For achieving the same result we can do it more simplistic way:

Besides, we often need to validate the case for value/object is null or not. We usually do it the following way :

You can do this in a more simplistic way by using the Null-Coalescing operator:

Another scenario :

Use the null propagation operator instead:

6. Simplify switch statement

We generally write a switch statement in this way. There is no issue with it but C# 8.0 version introduces a more simplistic way of writing of switch statement which is more clean and readable.

C# 8.0 version simplifies the switch statement this way:

Pattern Matching Expression

7. Minimize exceptions

  • Throwing Exceptions as normal behavior is bad practice. While adding try/catch is cheap, actually throwing an exception is expensive. Therefore, include logic in the method to detect and handle conditions that would cause an exception. For example, checking if something can be parsed by calling int.Parse() and catching an exception, should be avoided. Instead, we can use int.TryParse() which returns false if parsing is impossible.

  • ‘throw ex’ causes to loss of the stack trace data. The stack trace of the exception gets rewritten to the line of code where we explicitly rethrow it. This means that we lose all of the valuable information about what caused the exception in the first place. This can make debugging the code very hard. Just use ‘throw’. Besides, use try/catch only if you need to catch the exception and need to handle it as well.

  • Bad Practice

  • Good Practice

8. Use FirstOrDefault() instead of First()

FirstOrDefault() works same as First() but there is a significant advantage over First(). First() returns the first element from a sequence, but if there is no record in the collection which matches input criteria then it throws an exception immediately whereas FirstOrDefault() can handle null values and it does not throw an exception.

Same scenario goes for Single or SingleOrDefault , Last() and LastOrDefault().

9. Use the “using” statement

using keywords in C# plays a vital role in improving performance in Garbage Collection.

The using statement ensures that Dispose() is called even if an exception occurs when you are creating objects and calling methods, properties, and so on. Dispose() is a method that is present in the IDisposable interface that helps to implement custom Garbage Collection. In other words, if you are doing some database operation (Insert, Update, Delete) but somehow an exception occurs, then here the using statement closes the connection automatically. There’s no need to call the connection Close() method explicitly.

The using declaration, which was introduced in C# 8.0, doesn’t require braces:

10. Default Interface Method

Before C# 8.0 interfaces only contain the declaration of the members (methods, properties, events, and indexers), but from C# 8.0 it is allowed to add members as well as their implementation to the interface. Now you are allowed to add a method with their implementation to the interface without breaking the existing implementation of the interface, such type of method is known as default interface methods (also known as the virtual extension methods).

The main benefit of the Default method is that it allows us to add new functionality to the interfaces of our libraries and ensure backward compatibility with code written for older versions of those interfaces. For a better understanding, please have a look at the below example.

By Vivasoft Team
By Vivasoft Team
Hire Exceptional Developers Quickly

Find Your Talent

Get Updated with us Regularly
Share this blog on

Hire a Talented Developer from Vivasoft

Lets discuss about your offshore project. We can Help you by our skillful Global team. You can take a free counciling by taking a schedule

Related Post