Blog Back to all posts View all authors

Clean Code Principles In C# Aka How To Write Projects That Don't Suck

by Dawid Kraczkowski
March 14. 2019

Clean Code Principles: Uncle Bob For C# In A Nutshell

A long time ago, I promised you an article about clean code with examples. Now it is the highest time to keep the word. In the first part of the post, I will give you some general tips concerning clean code principles, meanwhile, in the second part, I'll concentrate on examples written in C#.

Ready? I hope so! :)

A List Of Tips On Clean Code

1. Use meaningful names  

It doesn't matter if you choose a name for variable, method, class, subproject or anything else. There is one simple rule to remember here – name should mean something. Forget about using variables called “s”, “field1”, “list”, “array”, “asdfg” etc. While the code will be growing in volume, random names are going to be first chaos triggers.

2. Use convention

I bet all programming languages define some conventions of variables, methods or classes naming. I also bet they define general structure and code organization. A convention is not only a set of guides on how to write good code, but it is also about discipline and well, a concise organization of your work. If you and your team do not like default language convention, pick your own, but for sanity sake, stick with it!

3. Try not to produce unused code

Imagine the following situation. In your fridge, you leave meat that has a short expiration date and think “Tomorrow I will eat meatballs”. But the next day comes and you think “I am too tired to do a single thing, let's order pizza!”. Then you leave for a week for a planned vacation. Then you go back and it turns out that meat is magically still in your fridge but it stinks. Well, everything stinks. This happens if you write unused code – its easy to get rid of it when it is still fresh. However, if it is dead and lies fallow for the weeks there is no one brave enough to clean things up.

4. Pay attention to structure

Do not write model classes where you store services. It should be easy to tell where to find objects of concrete types, and what they do.

5. Comments and variable names in your native language  

It's wonderful that you are proud of your country and embrace the mother language but programmers should know and use at least one basic language – English. There is a high probability that fellow professionals from other countries who have a brush with your code will understand English. To sum up, remember to not make it hot to other developers.

6. The Ultimate No-Go

Never ever write methods where name suggests something else than it is happening inside a method body. This is a simple formula for avoiding a catastrophe.

7. Use project patterns

But use them if there are really necessary – I have seen large projects without any patterns but I have seen even more projects with patterns used wrong. Both cases are dangerous.

8. Do not write classes with too many lines of code

It makes code harder to analyze and maintain. Pick your lines wisely, leave only essential ones.

9. Write unit tests

They are really helpful in larger projects. This way, you can check if everything works as it should. But first, learn how to write them properly so they don't cause even more damage.

10. Try not to write redundant code.

Please?

11. Unused Code Rule Complement

In the point no. 3 I was talking about unused code, under any circumstances do not write unreachable code, which can be quite hard to detect.

12. Reuse written code

Yours, your colleagues and language specific as well. Also, write reusable code. Zero waste trend has a use for the IT world.

Use constructions appropriate to your needs – the same effect can be achieved in numerous ways but try to use the most suitable one.

13. Take some time to learn something new.

Finished task earlier? Brilliant. Now you can check if you can do better and improve.

14. If your language support constants, Use them everywhere they are needed.

15. Do not use comments to comment out unused code

You have svn or git, don't you?

16. “I am tired now, I’ll write here ToDo comment and take care of it later” - I believe you...

Did you mean “never” when you said “later”? Seriously, you can write ToDo comments when you are about to finish your work today, and you need to know what to do tomorrow but never leave “ToDo” comments if you know you will not be able to handle them.

17. Use proper indentation, code formatting etc.

Make your code gorgeous-looking'. Make your code easy to read.

18. Do not nest your code beyond limits

The code should be read vertically not horizontally.

19. Do not use magic numbers 

Consider that not everyone knows what “-1” or “10” means in your code. Use constants, enums even comments but make someone know what those numbers mean.

20. Try to avoid constructing vast methods

Split them into smaller pieces. It may turn out that you can reuse them.

21. Do not write a few instructions in one line.

22. Do not use obsolete technology

If you are about to write some code in technology that is no longer supported, think twice. Necromancy should belong to fantasy. Do you remember the fridge example?

 

I guess I could give you more and more piece of advice. I strongly suggest you to read and understand Robert C. Martin’s “Clean Code”. Personally, I believe most of theclean code principles present in this book are valid today.

 

Clean code practices in practice

Now let's begin the second part of this post – promised workshop.

 

Block of code

 

clean code principles, uncle bob, c#, clean code tips, block of code servocode.com

Mentioned above block of code is barely readable. You can remove some unnecessary code and add some lines to improve readability.

 

 clean code principles, uncle bob, c#, clean code tips, servocode.com

 

Reusability of code

 

clean code principles, uncle bob, c#, clean code tips, reusability of code servocode.com

 

The important aspect of being a programmer is checking if particular functionality is already present in available libraries. Here we have an example where a delegate is created although build in one can be used. Let's refactor this code a bit.

 

clean code principles, uncle bob, c#, clean code tips - servocode.com

 

You still have the event but of build in type. Additionally, make invocation shorter with special construction (“?” check for null) and improved performance a bit when you get rid of constructing new EventArgs.

 

Better construction

 

clean code principles, uncle bob, c#, clean code tips, better code construction servocode.com

 

Here you can do nothing beyond cosmetic code changes, but it still makes our code more readable which is also a part of clean code practices.

 

clean code principles, uncle bob, c#, clean code tips - servocode.com

 

Exception handling

 

clean code principles, uncle bob, c#, clean code tips, exception handling servocode.com

 

Actually, this one is severe. I’ve seen similar construction somewhere in the real and working project. Let's consider what is wrong with this code:

  • MethodWithReturn returns very general type
  • MethodWithReturn in one case returns an Exception object

As you can see, the exception is not used properly. Generally, those objects are not supposed to be returned. The logic of our application is therefore controlled by returned object type. Horrible.

 

clean code principles, uncle bob, c#, clean code tips - servocode.com

 

Take a look at this code. It still returns object type but at least I use proper exception handling mechanism.

 

Inadequate construction

 

clean code principles, uncle bob, c#, clean code tips, inadequate construction servocode.com

 

Here we have a brilliant example where you can use for each instead of "for".

 

clean code principles, uncle bob, c#, clean code tips - servocode.com

 

I know it looks pretty similar but finally, use a loop which is designed for elements iteration.

 

Checking list

 

clean code principles, uncle bob, c#, clean code tips, checking list servocode.com

 

As you can see, integers list is empty – there is no point in checking if has no elements as for each loop will do it for us automatically.

 

clean code principles, uncle bob, c#, clean code tips - servocode.com

 

Indentation!

 

clean code principles, uncle bob, c#, clean code tips servocode.com

 

Trust me or not, I have seen such terrible constructions way too many times and I never want to see them again. Hopefully, there are brilliant tools which can automatically clean such messy code.

 

clean code principles, uncle bob, c#, clean code tips - servocode.com

 

Magic numbers

clean code principles, uncle bob, c#, clean code tips, servocode.com

I bet you know what those numbers mean? Seriously, consider using constants or some enums.

 

clean code principles, uncle bob, c#, clean code tips - servocode.com

 

You see? I don’t really have to care which number is responsible for Valid state, what’s more, I can change it at will, and every reference will follow. That’s the power of constants.

 

Redundant code

 

clean code principles, uncle bob, c#, clean code tips, servocode.com

 

Here you can see a repeat of code. Let’s move it out of brackets.

 

clean code principles, uncle bob, c#, clean code tips, redundant code - servocode.com

 

Nested instructions

 

clean code principles, uncle bob, c#, clean code tips, servocode.com

 

I know it’s not many lines of code but you can reduce the number of brackets and nested blocks with this simple trick.

 

clean code principles, uncle bob, c#, clean code tips - servocode.com

 

Wrong types

clean code principles, uncle bob, c#, clean code tips, wrong types - servocode.com

Personally my favorite portion of code I have seen recently. You just need to use proper types and everything begins to look better :)

 

clean code principles, uncle bob, c#, clean code tips, wrong types - servocode.com

 

And finally, we have arrived at the end of my post. Hope you enjoyed it. Now go back to your work and make better code :)

 

Even More Knowledge For Ambitious Beasts

1. https://blog.codinghorror.com/code-smells/ - I know it is from 2006, but these smelly code warning haven’t changed since that time.

2. https://sourcemaking.com/refactoring - It’s all about refactoring

3. The first part of my clean code principles guide

 

SEE ALSO

How to use Bluetooth LE to control robot via smartphone so you can make your own army take over the world.

Dependency Injection - basic knowledge that is going to save your time and nerves.

contact us

Have an idea ? Let’s talk

Office in Rzeszow
Office in Warsaw
CONTACT US
CONTACT INFORMATION

GET IN TOUCH

Fill up the form and we will contact you shortly

Name
E-Mail
Message

Company information

Fill up the form and we will contact you shortly.

ServoCode Sp. z o.o.

Jasionka 954E, 36-002 Jasionka, Poland

NIP: 8133719852

REGON: 364182909

KRS: 0000611643

We are using cookies to provide statistics that help us give you the best experience of our site. You can find out more or switch them off if you prefer. However, by continuing to use the site without changing settings, you are agreeing to our use of cookies. Read more

close