October 28, 2021

Tips for .NET Dev, Part II

IT Tips & Insights: A Softensity Senior Software Developer shares .NET programming tips in this multi-part series.

By Gabriel Cordeiro, Senior Software Developer

The following is the second part in a series. Read Part I here.

Magic Strings 

This is something very easy to find during your career as a Developer, but it can be something very dangerous for your project/system. A magic string is a hardcoded value. In your mind, you think it isn’t going to change, but it’ll change — trust me.

Those values can be changed at any time, or can even be confused: “Should I let the first letter be uppercased, or not?” Is it “Adm” or “administrator”? And in a real project, you’re going to use User.Role in a lot of places.

Considering that your code compiles with a typo, can you imagine how hard it is to find a typo if you need to look in your entire project? It would be great if you didn’t have to look in all places — just one, right? Let’s see how we can do it.

Create an Enum called Role and change User.Role type from String to Role. Check here for more information about enum: Enumeration types – C# reference | Microsoft Docs

We can change the code as below:

Now, there aren’t any problems with typos. If we need to change the value of an enum, we only have to modify on the enum declaration. And if you need to change an enum name like “Custom” to “Default”, your code won’t compile until you change every point. 

#Regions

Regions are very helpful to organize your code. For me, writing code is similar to writing a book, and regions are a good way to split your chapters into sub-chapters. Let’s imagine that we have an interface for business rules. We also have a concrete class that implements all rules from this interface, but to be able to do it we had to create a few private methods. We can use regions to organize private and public methods. Let’s see how:

In this picture, we see how to declare a region. We can also see that it’s possible to minimize your entire region. Using regions, we create code that’s more readable and organized. 

Building organized and readable software should be our main purpose as developers. We can’t apply concepts like SOLID, OOP, Clean Architecture, and others without doing the basic, Readable names, organized classes and small functions. 

About

Hey there, I’m Gabriel. I’m 24 years old and I’ve been a software engineer for almost 7 years. Currently, I’m a Senior Software Developer at Softensity. Most of my experience has been coding with C# from Microsoft, and I’ve learned a lot of cool things in this amazing language, so I thought I’d share some tips, both for C#, and programming in general. 

Join Softensity’s Team

BACK TO MAIN PAGE

Let’s Talk