Lesson 15 - The most common C# beginner mistakes - Naming variables
In today's C# .NET tutorial, we'll show first good coding practices in C# .NET. Not only beginners often violate them and make unnecessary mistakes in their programs, maybe you make them too?
Word of the senior programmer
Congratulations on mastering the first lessons of C# .NET Basic Constructs!
I prepared the material for today's lesson based on 20 years of my programming experience. As the editor-in-chief and lecturer, hundreds, maybe thousands of source code created by the community have passed through my hands. It wasn't difficult to notice that most of them, even though they work, contain unnecessary mistakes, which are also repeated over and over again. Surprisingly, mistakes were often made by both novice and more experienced programmers, and I used to make them too when I was learning to code.
I have come to the conclusion that the basic and wrong idea is:
✗ The program is correct if it works.
Programs and houses
If we build a house that we like and it doesn't blow into, it doesn't mean it's right. A house must have a well-thought-out architecture, and if it has no foundations, it'll start to collapse in a few years.
Programming is often compared to civil engineering in terms of architecture. Let's explain why.
Human brains can only work with a limited amount of information at a time. Simply said, if a program is poorly written, sooner or later the programmer would have to keep more things in mind than one can. Adding more and more functions to such a program will always cause an error in the application. In practice, it turns out that an author's hobby project "stops entertaining him" or a commercial project goes bankrupt because it's "already too complicated".
Let's take another example - When is our household arranged so that a hammer is in a first-aid kit, which is in the basement, it'll be probably difficult for us to work effectively in it. Although this example sounds absurd, its software alternatives happen daily.
When is the program correct?
It's simple. The program is correct if:
- it works
- it's in line with good coding practices and
- it's tested.
Note that the functionality from the user's point of view represents only 1/3 of the program's quality criteria. Like the functionality of a house from the resident's point of view represents only a fraction of its real quality in terms of civil engineering.
We'll be talking about the violation of good coding practices and the code quality today. We care about you being really good, so you can find a few more of these lessons across our courses.
How to name variables correctly?
It's said that 10% of the time we program something and 90% of the time we come up with a name for it This is, of course, an exaggeration, but the joke comes across a need to spend some time figuring out variable names. So that everyone, including us, when we return to our own code after a few months, understands what each variable is for. In general, you can rely on the simple rule:
We always name variables according to what they contain, not according to what they are used for in the program.
Let's compare the following two examples:
✗ Wrong
string print, text2; int[5] array; int foo, bar, x, calculation;
✓ Correct
string title, name; int[5] answers; int i, j, bonus, totalBonus;
Both examples create variables for a simple console quiz. In the first
example, it isn't clear at all what some variables contain, e.g. naming the
variable array
has about the same meaning as we'd call it a
variable
.
A common mistake is that we want to save the result of a
calculation, for example, and we name the variable
calculation
. However, the calculation isn't related to the variable
at all, it's an action, variables always contain a
value (the result of an action). This is the case with the
totalBonus
variable in the quiz. Similarly, in the first example is
a variable named print
because we print it somewhere. But we can
clearly see from the second example that it contains the title of the quiz.
Hand on heart - which one of you would understand that the code on the left is a quiz program?
We also never name variables temporary
or
temp
, etc.
Pay attention to "Spanglish" and accent characters
In the source code, at our beginner level, it doesn't matter in which language we'll name variables. To be as versatile as possible, it's best to write the code in English.
We name variables in one project in one language and if for example in Spanish, then without accent characters!
Let's show examples again:
✗ Wrong
string notificación = "Hi!"; int count;
✓ Correct
string notification = "Hi!"; int count;
Or:
string notificacion = "Hi!"; int contar;
We never use accent characters (ó, Ň, ...) in identifiers (e.g. in variable names). Of course, we can use them in values stored in those variables.
Although modern languages support UTF-8 encoding in identifiers, it's very easy to forget an accent and then use completely different variable! In addition, a source code file can be processed by an application that doesn't support it, and this will typically happen over time (for example, sometimes there's a problem with displaying diacritics in an attachment by a mail client, etc.).
Multiword variables
Today's applications are increasingly complex. It often happens that one word
isn't enough to describe what is stored in a variable. Then it's useful to use
more words. Nowadays you can come across relatively long variable names such as
userObjectOutputStreamFactory
.
However, such a long name only makes sense in a complex
application, where there are several similar variables, so we have to add
another word. So in a "Hello world" application we won't create a variable
named textWithGreetingHelloWorld
, but we can simply name it a
greeting
, if there isn't any other greeting
Separating words
For the sake of better readability of such a variable name, we must somehow separate the words:
- We separate several words according to the convention of the given
programming language. In C# there's
camelCase
, where every other word has a capital letter and the variable name then looks like humps. In other languages, for example, an underscore assnake_case
and other notations can be used. - If possible, we avoid numbering variables and don't write numbers in words
at all, neither
greeting2
orgreetingTwo
. "Two" says nothing about what that variable contains.
Let's look at examples:
✗ Wrong
string message1; string messageTwo;
Here it isn't clear what is stored:
string received; // text, bytes, a message, an order, ...? string sent;
And here the name is unreadable:
string receivedmessage; string sentmessage;
✓ Correct
string receivedMessage; string sentMessage;
We don't use abbreviations
Let's start this chapter with the quote:
Everyone wondered what the
DATBIR
column was for. Once it was discovered that it's apparently the date of birth.
This bad coding practice is basically the opposite of multiword variables. We
don't come up with nonsense abbreviations, for example, no one knows that
rm
means receivedMessage
. You can simply follow this
rule:
If someone other than us looks at the code, they should know what exactly is in each variable.
✗ Wrong
string me; int mc;
✓ Correct
string message; int messageCount;
As we promised, we'll return to the topic of good coding practices a few more times in similar, rather relaxing lessons
In the next lesson, What are algorithms for? , we'll introduce the world of algorithms, talk about what an algorithm is and why we should be interested in something like that at all.