How to Write Clean Code in C# (Less With The Mess)

tarihinde gönderildi - Son değiştirilme

In any language, be it C, Java or Python,  clean program code is desired. Clean code indicates the skill of a good programmer. You may be able to distinguish good artwork from bad, but that does not necessarily mean you are a good artist. Similarly, it is easier to identify clean code than to create it in the first place.

A good programmer should have a proper code sense which means they should be able to identify clean codes, and write them, without committing errors. In this article, we will see how to write a clean code in C#.

Argument should be validated first

Occasionally, people write functions in the case of invalid argument first. For example, take the case of finding whether a number is even. You can approach it in two ways - you can check whether the number is divisible by 2 and print that the number is even, for a valid argument. Or you can check if the number is not divisible by 2, and print that the number is not even. 

Always go for the valid argument first. This gives a clear idea about the intention of the program. If not, the reader will need to go to the end to figure out the objective of the function. This problem becomes more visible in the case of lengthy codes.  If the valid argument is mentioned first, the reader can quickly understand the purpose of the function at a glance.

Avoid “else” when Possible

Consider the case when you are looking for a single exception. For example, you may need to find a prime number from a group of numbers. The occurrence of a prime number is rare. Let there be 2 prime numbers in a group of 50. So, you only need to print the prime number. In the case of a non-prime number, you cannot do anything. In such situations, “else” is better avoided. This reduces unwanted indentations and makes the code cleaner.

Curly braces

There is a mixed opinion about whether to use curly braces or not. Obviously, they improve the readability and help distinguish various function bodies. However, braces may not be necessary for all situations. It is advisable to use curly braces, but it is always your choice to use it or not. That said, make sure you don’t commit any syntax errors in the process.

Give Meaningful Names to Identifiers

The name of your identifiers should hint at their usage. For a function to add members, name it as addmember. If you name it am, it may seem enough, but a person reading your code may not understand.

The names should give an idea of what the identifier is all about. Don’t consider the length of the name. Be clear with names so as to give sufficient information. 

The casing of letters is also a method to make your code clean. For example, if you use AddMember instead of addmember, it will give more visual appeal to your code. The variable can start with a lower case or an upper case, but the subsequent words in the variable should preferably start with an upper case letter.

Avoid Redundant Variables

In olden days, programmers used to declare the entire variables they used. Even for a simple function, there would be a lot of variables. This should be avoided.  Only name the variables if they play a crucial role in the program. Also, keep the readability of the program in mind.

By not naming each and every variable, you are making the code cleaner. There is no need to name temporary variables whose function is over in a couple of lines. 

Avoid Code Smell

A code is said to be smelly if it is dirty. There are many reasons for this. The code may be too complex with a lot of redundant variables. It may contain duplicated or outdated code instances. Classes may contain too many instance variables.

Avoid all these to make your program clean.

Proper Declaration of Types

You should declare the type of variables you use in the program. It avoids many bugs. If a numeric variable is not declared, it may cause confusion in the minds of the reader. It may be an integer or a float. So be clear, and specify your variables.

All programmers may not identify the type you had intended for a variable. In some cases, as in a loop incremented variable, the variable will be an integer. This may not be the case for all. So, to be on the safe side, always declare your variable types. It will ensure proper memory allocation too. This is of great help when programs need revision.

Place the variable declaration close to where you intend to use the variables. If they are declared far away from their usage, confusion arises.

Psychological Aspects

A clean code is best written when your mind is fresh and stress-free. It is impossible to work for a long period, keeping your calm. As a programmer, you shouldn’t overstress yourself. Take periodic breaks and keep your mind clean. When you cannot focus sufficiently, the code you write will always contain errors. It will not have a proper structure, and won’t meet the requirements of your customers. 

The environment also plays a part in creating clean codes. It is difficult to focus when it’s noisy. While working on complex codes, it is wise to shelter to a quiet place. Try to keep distractions to a minimum.

When you are too overloaded with work, take the help of freelancers on the internet. Freelancer.com is a great website for posting your project, if you need a helping hand.

Learn and Improve Yourself

As somebody rightly said, you are a student till your last breath. Life gives you many things to learn. Keep reading books - not only technical but also informational. Always sharpen your skills and stay up to date with what’s going on.

Always add something new to your skill set. Don’t try to master everything, but do read up on new languages and frameworks, and know their basics. You get better by practice. Your codes will become clean as you progress along your professional career.

A programmer will rarely be out of work. Browse Freelancer.com for thousands of programming projects. You can always find some additional work when you are idle at the office (if it ever happens!).

Advantages of a Clean Code

cleaner code is easier to read, so make sure your code is not too lengthy. But do keep it short wherever possible (though not at the cost of readability). We have now learned ways to make the code cleaner. Now, let us look at the advantages of a clean code.

  • Comments are the key to readability. You may not understand your own code after a time gap, but with the help of comments, you can ensure the reusability of your code. It ensures fast debugging, and development of your code.
  • Once people can understand your code, they start to appreciate it. It is a misunderstanding that complexity gives your code a geeky appearance. The truth is that complex things coded in a simple way are often most admired. You will admire clean codes when you find a bug. Readability is when you can express your code in the simplest of languages, and it helps you debug without losing your mind.
  • Write your code in such a way that your coworkers can easily understand it. In case you have a development director, readability will play a crucial role. According to Moore’s law, readability receives an upper hand over premature optimization.

Did we miss any tips? Let us know in the comments below!

Gönderildi 7 Ağustos, 2017

LucyKarinsky

Software Developer

Lucy is the Development & Programming Correspondent for Freelancer.com. She is currently based in Sydney.

Sonraki Makale

17 Killer Tips for Developing Android Apps Using Kotlin