Naming is more important than what you might think!

Have you ever wonder why we end up with large classes or methods with hundreds of lines, if not thousands. Surely, we don't start out with the intention to make them that large. We are even fully aware of this issue, but what happens that we do it anyway? 
I would argue that possibly the strongest reason for this issue is naming. Here's why! If we want to break long methods or classes into smaller ones, we need new names for those small ones. On the other hand, naming requires a lot of cognitive loads and can be challenging, so we tend to avoid it. Instead, we keep piling more code into existing methods to bypass naming.
Naming is one of the hardest yet most important things to do in software development, but it doesn't have to be painful. Naming is a skill, and with some practice, we can acquire it. 

Our primary goal

I'm going to explain how I do naming but first, let's step back a bit and see why we need to pay attention to naming. When we write code, our primary goal is to communicate our intention or knowledge with other developers or even our future selves. To do that, honestly, we don't have many options. The programming languages' syntaxes are very restricted, and the only place we have freedom is naming. So, we really need to make sure that we don't miss out on this opportunity; otherwise, our code becomes hard to understand.

Context

Anything we name already exists within a context, and we shouldn't include the context in the name. Despite how obvious this fact is, still, so many people tend to miss it. For example, if we have a Player class, it should have fields or properties like ID, Name, or Speed, not PlayerID, PlayerName, or PlayerSpeed.

Structure

While writing code, we often name a lot of things that have similar characteristics. We can use or define a structure for those names to save ourselves from creating unnecessary unique names. For example, the result of a method can be called ''result' regardless of its actual type.
ObjectType someMethod()
{
    ObjectType result = new ObjectType ();
    // Some code here to prepare the result
    return result;
}

Another example is when we name events and event handlers. We can have the following structure:
event's name: [subject][past tense of verb]
event's handler: On[subject][past tense of verb]
Example events:
GamePaused
PlayerDied
EnemyEnteredDangerZone
Example event handlers:
OnGamePaused
OnPlayerDied
OnEnemyEnteredDangerZone

Final thoughts

There is a lot more to naming effectively than what I can fit into a single blog post. Also, there are so many materials on this subject on internet that I don't want to repeat here. The important thing to remember is that naming is the first and foremost vital skill we should learn to write clean code.

Comments

Popular posts from this blog

Implicit coupling will stab you in the back!

Unity Project Folder Structure

Why this blog?