Serengeti logo BLACK white bg w slogan
Menu

7 Important Tips to Write Code in C#

Petar Jaredić, Mid Software Developer
26.10.2021.

Writing code is not difficult – but writing code that tells a story can be. This post is intended for those who want to be better C# developers.

Do you want to develop software that is both beautiful and easy to maintain? Today I will try to present the best practices for writing quality software in C#.

1. C# Regions are Design Smells

The Regions feature in C# is frowned upon by many. There are good reasons for that. I will use this opportunity to try to explain why not to use them.

Regions are one of the strongest smells in C#, in a sense that it’s hard to justify their usage. If you see one in a code, it is always a sign that a bad design decision has been made.

Let's look at an example:

public class SomeClass

{

-field

-constructors

-properties

-public methods

-private methods

-static methods

public void DoSomething(string a, int b)

{

    #region Validation of arguments

    if (a == null)

    {

        throw new ArgumentNullException("a");

    }

    if (b <= 0)

    {

        throw new ArgumentOutOfScopeException("b", ...);

    }

    #endregion

    #region Do real work

    ...

    #endregion

}

}

This style often aimed at hiding that a class is too large and thus violates the SINGLE RESPONSIBILITY PRINCIPLE. If there is a problem with the code, don't hide it! State it!

2. Bad Names for Classes, Variables, and Methods

Have you ever worked on a project that had problems like these? If the answer is yes, then I’m sure you will understand what I’m trying to say.

In the days of Visual Basic, we used to use Hungarian Notation. We don't need that in C#; it makes your code look ugly. The use of cryptic names and names that don't seem to match the intention of the code can make the code rather difficult.

Don't use underscores between words in a name either, such as Bad_Developer. This can cause visual stress for the programmer and can make the code hard to read. Simply remove the underscore.

The name of a variable, method, or class should tell what it is doing – the name of a variable is always a noun, the name of a method is always a verb!

A good naming convention for variable names is to use Camel case for variables such as goodDeveloper and Pascal case for methods, classes, struct and interfaces.

Let’s look at the following example:

 public class SomeClass

{

private int m_field;//Hungarian notation

public int Property{get;set;}//Pascal case

public void SomeMethod(int parameter)// method in Pascal case, parameter in Camel case

{

}

}

3. Magic Numbers and Strings

When you see strings in the code, you need to define them as constants or variables with different methods. This will help other programmers reading your code to understand its purpose.

By using magic numbers, you're making your codebase hard to understand and maintain. If any value is changed, you will have to go through all your codes and make necessary changes.

For example, let's say you are comparing a local variable with the number 5. If the given condition is satisfied, then you execute a particular code insight of the block. The problem here is to understand what the number 5 means in the content. Sure, you will understand it at that moment, but if you go back in a few months, the chances are that you will forget what the value means. To avoid this practice, use SYMBOLIC CONSTANTS for such magic numbers.

4. God Object

God object is a term for a class that has many responsibilities.

Let’s say we have a class that connects to database, gets data, manipulates the data, loads the reports, displays the reports, prints the reports. This class does too much.

While many factors can cause a class to increase in size, one of the most common factors is static methods. They get called from different parts of the solution.

Solution: use the Extract class or Move method refactoring to make the class smaller.

5. Long Method

Long method is a method that contains too many lines of code. But how many is too many?

It is hard to specify a certain number. But the point is not in the number of lines. It's the work that it does. If the method does more than one thing, you should consider changing it because smaller methods are easier to understand. The best solution is moving a part of the logic into another method.

Long methods are a code smell and need to be refactored. They can make it hard to add new features or to modify existing ones, and they are also more difficult to understand, to test and harder to reuse.

Solution: Use the Extract method or Introduce Method Object refactoring. The Extract method is a technique that takes up several lines of code and moves it into another method. The name of the new method explains what the method does. This is a good example of the DRY PRINCIPLE, which states that the code that implements a single functionality should not be repeated.

6. Duplicate Code

Duplicate code is a bad code smell. It is one of the most common smells found in code because it is in human nature to copy code. You find the solution that you need in the existing code and simply paste it into a new location. PROBLEM SOLVED.

The lack of understanding about the purpose of duplicated code can lead to a deeper problem. There are many reasons why duplicate code is bad. First, when you have duplicate code, you increase the risk of introducing the same bug to a new place. Secondly, if you need to change code to add a new feature and you have the same code somewhere else, you need to remember to go to all other places and see if you need to change it there as well.

Solution: Use Extract Method refactoring to move the code to a new method, which you can call from different places.

7. Long Parameter List

A long parameter list is a code smell because it can be a sign that a method is doing too much. What is the optimal number of parameters? It depends on the context and the code you are working with. In his book 'Clean Code', Robert C. Martin (known as Uncle Bob) states that a method with three or more parameters should be refactored. If the method has more than three parameters, that’s a sign that something is wrong.

Let's take an example:

public class Person

{

public bool UpdateName(string firstName,string LastName,int age,double height,double weight)

{

firstName = "Joe";

lastName = "Johnson";

age = 34;

height = 185;

weight = 80.4;

return true;

}

}

Too many parameters, do you agree?

Let’s fix it:

public class PersonParameter

{

public string FirstName {get;set;}

public string LastName {get;set;}

public int Age {get;set;}

public double Height {get;set;}

public double Weight{get;set;}

}

public class Person

{

public void UpdatePerson(PersonParameter person)

{

person.FirstName = "Joe";

person.LastName = "Johnson";

person.Age = 34;

person.Height = 185;

person.Weight= 80.4;

}

}

Not bad, but we can go one step further. Let's see that step.

public class PersonResult

{

public bool Success {get;set;}

public string Message {get;set;}

}

public class PersonParameter

{

public string FirstName {get;set;}

public string LastName {get;set;}

public int Age {get;set;}

public double Height {get;set;}

public double Weight {get;set;}

}

public class Person

{

public PersonResult UpdatePerson(PersonResult person)

{

person.FirstName = "Joe";

person.LastName = "Johnson";

person.Age = 34;

person.Height = 185;

person.Weight= 80.4;

return new PersonResult

{

Success = true,

Message = "We are good"

};

}

}

Solution: Introduce Parameter Object, Preserve Whole Object, Replace Parameter with Method Call refactoring.

Conclusion: In conclusion, code is an ever-changing beast. Like all other beasts, it can smell from time to time. This post has identified the most common code smells.

In the next post, I will explain other smells that could be in our code.

Let's do business

The project was co-financed by the European Union from the European Regional Development Fund. The content of the site is the sole responsibility of Serengeti ltd.
cross