Tips For Writing Clean And Concise Code In C#

Introduction

In this article, we will discuss some very cool tips for writing clean and concise C# code for more maintainability and understanding. We’ll discuss how we can write a very few lines of code to do the same job that is done with so many lines of code.

These little tips and habits really matter a lot when your application starts growing and you want to organize your code in the best possible way you want, so that other team members can understand your code easily.

Tip 1 Prefer Inline Logics

Inline logics evaluate and return results within a single line. Inline logics are very useful for defining simple algebraic expressions.

Simple Example

For example, you have a scenario where you need to return true if a specific value is equals to 10, you can solve this problem in many possible ways but here we’ll discuss two possible solutions.

Solution 1 You can solve this problem using if else block.

But look! Here, we are solving a problem with 8 to 10 lines which is not very smart.



Solution 2 You can solve this problem by writing inline Logic.



Two lines doing the same job of 9 to 10 lines

Ternary Operator Example (? )

From the above example, we are returning bool from expression but what if we have to return something else other than bool and we also want to preserve the conciseness and cleanness of our code? In C#, we use ternary operator for defining inline logical if statement to return the result of any type.

As always, we’ll discuss two possible solutions here. Let’s take the above example to the next level but here, we will be returning a text message instead of bool.

Solution 1 We can use if-else statement to solve the problem



If-else statement is very important and often used in many scenarios where we have to take a decision but in cases where we have simple logics to evaluate we can write a little bit cleaner code using ternary operator.



Ternary operator evaluates the first part if the condition is true and the second part if the condition is false.

Null Coalescing Operator Example (??)

Null-Coalescing operator is used to check for null values, if the operand on left side is null then it will return the operand on right side otherwise in any case if the operand on left side is not null then it will return value of operand on left side itself.

Let’s take a look at the demo code without using null-coalescing operator.



Using null-coalescing operator we can do the same job in one line.



Tip 2 Else block is not always Necessary

if-else block is often used for making decisions like If the value is that then do that and if the value is not that then do something else. Many times, we need to define else block after the if block which is not necessary to define every time.

Let’s take the previous example of making decision on value==10, usually we’ll write code like this:

The else block that we are defining here is not necessarily required, we can do the same job without the else block.

If logic evaluates as false, then if-block will not be executed and controller will start execution automatically at the very next line from end of if-block.

Tip 3 Prefer String interpolation

String interpolation is used to insert dynamic values at runtime in string of text. String interpolation is a new feature added to C# 6.0. Before C# 6.0 we have to use string concatenation and string placeholders for that purpose. After C# 6.0, string interpolation is preferable, cleaner and a more efficient way to interpolate dynamic values in strings.

For example, we have to add an Artist name and email to a string, using string concatenation you’ll use plus (+) operator for insertion of dynamic values.

But string concatenation is always a bad practice because of immutable nature of string in C#. It will always create a new object of string as per concatenation, that’s why string concatenation is bad in terms of memory management.

With string interpolation, we can do the same job in a cleaner and more efficient way.

All you need is to add a dollar ($) sign in front of string, after that you can insert dynamic values using braces “{}” directly within string.

String interpolation will create only one object of string on heap in that case.

Tip 4 Declare Variables Close to Use

Always declare your variables close to where you use them. If you have declared a variable far away from use, then other developers may even get confused about the use of variable.

If you are seeing your code after a long time, then there are chances you even can get confused about the use of your variables.



Tip 5 Use expression bodied Methods

Expression bodied methods are preferred to use in cases where your method definition is greater than the actual method body. In expression-bodied methods instead of writing the whole method body we make use of lambda arrow to return from method in one line.

Tip 6 Avoid declaring too many variables

Always try to avoid declaring too many variables. Too many variable will make your methods fatter and confusing. Instead of declaring variables I’ll suggest to inline them.

For example, a bad practice can be this one below.

In the above snippet, we are declaring some extra variables that we don’t really need to declare. We can use inline variables instead.

Now that looks a lot better and wiser.

Tip 7 Too many parameters are annoying

Having too many parameters for methods is irritating. If too many parameters are required, then instead of providing those values individually you can wrap then in an object and accept the object instead.

Accepting a wrapper class instead of enormous parameters would be much cleaner.



Tip 8 Don’t allow your Methods and Classes to get fat

While working on an application initially we focus on  the functionality part,  have no rules to follow, we just put things wherever we want and make sure application functionality is working properly. But as the application grows things start messing up and it becomes hard to manage the code. Growing business needs and bad architecture design will lead us to further problems of maintaining and testing.

Moving toward clean architecture will always be the best choice, putting things where they belong. Don’t ever allow your classes and methods to do side jobs that they never intended to do. Following below here we have examples of clean and bad practices of writing code.



Plan application layers and modularize code. Follow SOLID architectural principles while designing classes and methods. But the thing is, how much we should modularize our code?

Ans The simple answer to that question is as much as we can.

Each class must have a single responsibility and each method must have a single individual task to perform. Things having too many responsibilities are difficult to maintain.


On the other hand, things having a single responsibility are easy to maintain.


Similar Articles