Comments

5 Tips for Junior C# Developers to Write Cleaner C# Code

Many students of my C# Basics course submit their code in the discussion area, and when I get a chance, I review their code and give them hints to improve their code. I’ve noticed quite a few common patterns in the code submitted by junior C# developers. In this post, I’m going to explore these areas and share a few tips to write cleaner and more maintainable code.

1. Validate the input “first”!

Look at this code snippet:

public void Draw(Shape shape)
{
   if (shape != null)
   {
      Console.WriteLine("Drawing " + shape.ToString()); 
      Console.WriteLine("---");     
   }
   else 
   {
      throw new ArgumentNullException("shape");
   }

We have to read all this code to find the last line that throws an exception if the argument is null. By convention, we often validate the input first. This tells the reader of the code how a given method should be used.

So, let’s reverse the order of if and else here:

public void Draw(Shape shape)
{
   if (shape == null)
   {
      throw new ArgumentNullException("shape");
   }
   else    
   {
      Console.WriteLine("Drawing " + shape.ToString()); 
      Console.WriteLine("---");     
   }

Now, you can immediately tell what is a valid argument for this method. You don’t have to scroll down to the end of the body of the method to figure that out.

2. You don’t always need an “else”!

Continuing from the last example, if shape is null, we throw an exception and the rest of the method will not be executed. So, there is really no need to add that “else” block, which increases the indentation of the code. Here is a cleaner way to write this code:

public void Draw(Shape shape)
{
   if (shape == null)
   {
      throw new ArgumentNullException("shape");
   }
      
   Console.WriteLine("Drawing " + shape.ToString());
   Console.WriteLine("---");
}

Note that the rest of the code after the “if” statement is not indented.

3. Curly braces?

This one is subjective. Some developers love their curly braces, some don’t. I’ve gone through different phases. There is really no right or wrong here. Do your own judgment when looking at the code. Let’s remove the curly braces in the precious code and see what it looks like:

public void Draw(Shape shape)
{
   if (shape == null)
      throw new ArgumentNullException("shape");
 
   Console.WriteLine("Drawing " + shape.ToString());
   Console.WriteLine("---");
}

I think this code is cleaner. What do you think?

4. Pay attention to the name of your identifiers

Name of your identifiers is as important as the name of your children. I’m dead serious. No one wants to read someone else’s code with the following identifiers:

  • od: What is od? Oh Damn? Obsessive Disorder? Overdue Days?
  • Button1_Click(): What is Button1? How is it different from Button2?
  • thisAs: What’s that even supposed to mean?!

Use a name that clearly communicates the intent.

5. Avoid unnecessary variables

Back in 80s, programming books used to teach use to declare a variable for nearly everything! Look at this piece of code that reads two numbers from the console and prints the maximum:

var firstInput = Console.ReadLine();
var firstNumber = Convert.ToInt32(firstInput);
var secondInput = Console.Readline();
var secondNumber = Convert.ToInt32(secondInput);
var max = (firstNumber > secondNumber) ? firstNumber : secondNumber;
Console.WriteLine(max);

My eyes are popping out as I’m declaring all these variables! What is the focus of this code? Two numbers and their maximum. So, firstInput and secondInput, which are strings read from the input, are not the focus of the code. All we care about is a number read from the console. The temporary string we receive from the console is not the focus here. So, these two variables are not adding any value to this code in terms of readability. They’re just creating noise in the code.

We can read an input from the console and convert it to a number in one line:

var firstNumber = Convert.ToInt32(Console.ReadLine());
var secondNumber = Convert.ToInt32(Console.Readline());
var max = (firstNumber > secondNumber) ? firstNumber : secondNumber;
Console.WriteLine(max);

So, avoid declaring unnecessary variables. Use variables to increase the readability of the code.

If you enjoyed this post, please drop a comment and also share it with your peers. If you’d like to learn more tips for writing cleaner code, check out my course: “Clean Code: The Art of Writing Beautiful C# Code”.

Hi, my name is Mosh Hamedani and I am the author of several best-selling courses on Udemy and Pluralsight with more than 130,000 students in 196 countries. You can see the list of all my web and mobile development courses on this website.
Tags: , ,