5 Tips to Writing Clean C# Code

One of the most important skills of a C# programmer is writing clean, efficient code that performs well and can be easily maintained by others who will inherit your code after you’ve moved on to other projects. This can seem like an impossible task, as…


This content originally appeared on DEV Community and was authored by Dotnetsafer

One of the most important skills of a C# programmer is writing clean, efficient code that performs well and can be easily maintained by others who will inherit your code after you've moved on to other projects. This can seem like an impossible task, as there are many factors to consider when writing C# code, including variables, methods, classes, and types, just to name a few. But with these five tips, you can learn how to write clean C# code that's easy to read and understand by others on your team.

Use variable names that are easy to remember

This malpractice is one of the most common. Many times we  - the .NET developers -  want to complicate a lot when in most of the occasions it is not necessary.

When declaring a variable, we should use a name that makes sense, that is easy to remember and that is easy to pronounce.

Bad way:

var yyyymmdstr = DateTime.Now.ToString("YYYY/MM/DD");

Good way:

var currentDate = DateTime.Now.ToString("YYYY/MM/DD");

This does not seem to be important, but once the project develops and becomes larger, the number of variables will be very large. And we all know that when we open a project after a long time without opening it, many times we don't know what some part of the code does.

Use variable names with the same structure

Many times it has happened to us that we declare variables but we declare each one with a different structure or  - lexically speaking - with a different vocabulary. Let me explain:

We should always look for the greatest simplicity. We should always use the same word and not vary it  - I mean synonyms. Let's see a practical example.

Bad way:

getUserInfo();
getClientData();
getCustomerRecord();

Good way:

getUser();

In that example, we can clearly see that in the bad way we are using different synonyms for the same word. This may cause confusion in the future, both for the current developer and for the (possible) future developer who will have to understand the code.

Use searchable names

I am sure that more than once you forget where something is and you start looking for that something but you can't find it because you don't remember what name you gave to the variable or directly, you don't remember if you named that constant. For your better understanding:

Bad way:

// In the future we will not remember what 86400000 means.
clearBacklog(backlog, 86400000);

Good way:

// Declare constants with a searchable name
var MILLISECONDS_PER_DAY = 60 * 60 * 24 * 1000; //86400000;

clearBacklog(backlog, MILLISECONDS_PER_DAY);

This small practice, although it may not seem like it at the time, will save us many hours of searching and quite a few headaches (both for us, the current developers, and for potential future developers). Remember: The easier to read code, the better.

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 way:

Bike MountainBike = new(){
   bikeBrand = "Trek",
   bikeModel = "MX Mountain",
   bikeColor = "Green"
};

void paintBike(Bike mountainBike, string color){
     mountainBike.bikeColor = color;
}

Good way:

Bike MountainBike = new(){
   brand = "Trek",
   model = "MX Mountain",
   color = "Green"
};

void paintBike(Bike mountainBike, string color){
     mountainBike.color = color;
}

In this way we can see that by spending less time thinking and writing, we get a much cleaner and easier to read code (which we will thank ourselves in the future for having done).

Uses highly descriptive variable names

Another bad practice is to send functions directly as an argument of another function. This only causes a lot of confusion and makes our heads hotter than an old AMD FX series processor.

Bad way:

const address = "One Infinite Loop, Cupertino 95014";
var cityZipCodeRegex = new Regex(@"/ ^[^,\\] +[,\\\s] + (.+?)\s * (\d{ 5 })?$/").Matches(address);
saveCityZipCode(
  cityZipCodeRegex[0].Value,
  cityZipCodeRegex[1].Value
);

Good way:

var address = "One Infinite Loop, Cupertino 95014";
var cityZipCodeRegex = new Regex(@"/ ^[^,\\] +[,\\\s] + (.+?)\s * (\d{ 5 })?$/").Matches(address);
var city = cityZipCodeRegex[0].Value;
var zipCode = cityZipCodeRegex[1].Value;
saveCityZipCode(city, zipCode);

The solution, as we can see, is to add the resulting values in variables and then send those variables to the function. This will allow us to understand in a simpler way the information that you are sending to it and besides, we will save a Noctua heatsink for our head.

I know these little tips are pretty simple (although I'm sure not all of you will follow them😏). The number of ways to write cleaner code in C# is more infinite than the universe. So, I'm going to make a list of Cleaner C# Code posts, in which, we will touch on more advanced tips and some other tricks to improve the quality of our code.

If you are interested, don't forget to follow us so you don't miss any news!


This content originally appeared on DEV Community and was authored by Dotnetsafer


Print Share Comment Cite Upload Translate Updates
APA

Dotnetsafer | Sciencx (2022-02-09T11:33:06+00:00) 5 Tips to Writing Clean C# Code. Retrieved from https://www.scien.cx/2022/02/09/5-tips-to-writing-clean-c-code/

MLA
" » 5 Tips to Writing Clean C# Code." Dotnetsafer | Sciencx - Wednesday February 9, 2022, https://www.scien.cx/2022/02/09/5-tips-to-writing-clean-c-code/
HARVARD
Dotnetsafer | Sciencx Wednesday February 9, 2022 » 5 Tips to Writing Clean C# Code., viewed ,<https://www.scien.cx/2022/02/09/5-tips-to-writing-clean-c-code/>
VANCOUVER
Dotnetsafer | Sciencx - » 5 Tips to Writing Clean C# Code. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/02/09/5-tips-to-writing-clean-c-code/
CHICAGO
" » 5 Tips to Writing Clean C# Code." Dotnetsafer | Sciencx - Accessed . https://www.scien.cx/2022/02/09/5-tips-to-writing-clean-c-code/
IEEE
" » 5 Tips to Writing Clean C# Code." Dotnetsafer | Sciencx [Online]. Available: https://www.scien.cx/2022/02/09/5-tips-to-writing-clean-c-code/. [Accessed: ]
rf:citation
» 5 Tips to Writing Clean C# Code | Dotnetsafer | Sciencx | https://www.scien.cx/2022/02/09/5-tips-to-writing-clean-c-code/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.