Naming Matters

Choosing a name has a huge impact on the readability of the code.

In this post, I will walk you through some of the bad and good examples which might convince you why naming matters.

Project directories:

Three projects, guess which one is admin site, native mobile app, and restful API?

Can you guess which project serves as an admin website, mobile app, and server-side API’s?

Here, The developer not only failed to give attention to naming but also masked his original intent of each project with some other words. Confusing?


The sentence:

P and Q went to R. They had a good dinner at S followed by T and then they came back to U.

Could you read the above sentence, understand its clear intent and reconstruct it after hours even though it’s a small sentence?

For me, it’s difficult to understand due to the usage of abbreviations. It will lead me to make different assumptions.


Code snippet:

Random code snippet

I am sure you have figured out what is this small code snippet doing. However, it was not that easy even though it was a small code snippet.

Now think about a project that contains more than 1000+ classes, modules, methods, files, and many more.

The complexity and frustration will be increased in the same magnitude if developers don’t give attention while naming those.

Don’t you think it will be painful for the maintenance developer as well as your future-self to visit and understand the intent behind the code?


Real-life analogy

Everything in this world has meaningful names. It helps our brain to understand, remember and figure out the things at ease. It means less mental mapping.

Photo by Bernard Hermant on Unsplash

When you visit hypermarket, you could easily figure out groceries, fruits, cosmetics and so on.

You could easily fetch handwash, facewash, aftershave, sanitizer, liquid sanitizer, moisturizer, cold-drinks, cookies, water bottle and so on. Thanks to proper naming to the categories, items and so on.Naming matters!


Let’s revisit the above examples with careful naming.

Project directories:

Uglier way:


Three projects, guess which one is admin site, native mobile app, and restful API?

Better way:

See projects after renaming, are you able to figure out which one is admin site, mobile app, and API at ease?

The sentence:

Uglier way:

P and Q went to R. They had a good dinner at S followed by T and then they came back to U.

Better way:

Tom and Jerry went to a Mall. They had a good dinner at a restaurant followed by a movie and then they came back to their Home.

Do you realize the power of effective naming?


Code snippet:

Uglier way:

Random code snippet

Better way:

Find the Volume and Surface Area of Cuboids

Just looking at code snippet, it is crystal clear that code is working on height, length, and breadth to compute surface area and volume.

Now with proper naming to the variables, A small code snippet with careful variable naming makes developers life easy.


Imagine what will happen to readability, understandability, and maintainability if you show the same dedication while naming everything in the project.

We as a programmer try to solve the customer requirement or problem by creating various projects.

These projects may have directories, assemblies, namespaces, packages, files, classes, modules, properties, fields, events, method arguments, method parameters, UI elements, UI attributes, UI styles, validators, services, translation files, translation keys, command-line utilities and many more.

All of these things should have a meaningful name so that they convey their intent. You should be able to figure out what they are doing by just looking at their name.

Perhaps they should answer all the big questions that you or future maintenance developers would have.

Naming matters! Please give attention to naming everything in the programming!


Dattatray Kale | Being software craftsman
I am an application developer based in Pune, India. I am willing to wait for the right opportunity – Datta CV PRACTICES…blog.beingcraftsman.com

Replace magic number with named constants

120308

What do you understand after reading the above number?

It is just raw data. The interpretation is left to the reader of the data.

However, the reader may not get the intent behind it.

  • It could be a zip code of a city.
  • It could be a birthday in DDMMYY  format.
  • It could be a telephone number without the area code.
  • It could represent N number of things.

Do you agree with me that using just raw data does not convey its intent?

Similarly, a magic number in code is like raw data which does not convey its intent to the reader of the code.

A magic number is a numeric value that is used in the code. This value has unexplained meaning and hampers readability of the code.

Above code reads like John failed to upload his profile picture because the size of the profile picture was more than 10000000.

Here I did not understand the meaning of magic number 10000000.

Whether it is a size in Bits, Byte, KB, MB, GB?

Well, let’s introduce the named constant and see what happens.

Now, the code reads more like John failed to upload his profile picture because the size of the profile picture was more than maximum allowed file size i.e. 10000000 bytes.

As soon as you give metadata about the data i.e. relevant data it becomes information to the reader. The reader can work with it easily as the intent is clear.

Another example:

Bad way

When the given day is 0 or 6, Magic number! then put ‘-’ in cell content.

Better way

When the given day is Sunday or Saturday then put ‘-’ in cell content.

Thus, named constants could be used to provide data about raw data so that reader of your code could easily figure out the intent.

Hence, Replace magic number with named constants.

Encapsulate conditionals

Conditionals play a vital role in code for performing business decisions. These conditionals should be easy to read.

If conditionals are complex then it might hamper readability. You would end up introducing more bugs if failed to understand its intent. Every time you visit this code, you will need to debug it to understand the intent.

Complex conditionals:

Complex conditional determines something to perform business rules

Look at above conditionals in if clause. It is clear that it is performing too many checks related to the package of the items. Please note that this package was ordered from an online e-commerce site and then performs important business decisions.

It will be difficult for the maintenance programmer to figure out each condition and know what question it tries to answer.

Let’s make the maintenance programmer’s life a little easy by writing readable code using encapsulate conditionals that have intuitive names and give the answer in yes/no format.

Better way:

Complex conditionals are extracted to a method. 
An intuitive name is given that tells what it is doing.
The complex conditional block would be simplified like this. It reads like perform business decisions if a package is eligible for a return.

Another complex conditional

Too many questions here.

Preferred way:

A simplified version with clear intent: can view editor?

Dattatray Kale | Being software craftsman
I am an application developer based in Pune, India. I am willing to wait for the right opportunity – Datta CV PRACTICES…blog.beingcraftsman.com

Don’t be anti-negative

The negative conditionals in code blocks are most of the time difficult to read and understand.

It becomes worse when you make the conditionals anti-negative.

Before

Anti-negative conditionals

Try to read above code snippets and try to understand it. Please note the highlighted parts. Does that code reads like

  • When inverse of a package is not damaged then report an error: “Package is damaged”.
  • When inverse of a package is not empty then report another error:
    “Package is empty”

Ouch! Unreadable? Complex? Painful, isn’t it? Let’s revisit the same condition with positive conditionals.

After

Positive conditionals

Another example:

Before:

Set hours logged when it is not NonWorkingDay. What?

Above snippet is showing hours worked for the day if it’s not non-working day!

After

Set hours logged when it was working day.

Now, this reads like simple statement. Show hours worked for working day.


Extract Method

Extract method is the most frequently used refactoring technique. It reorganizes the code for better reuse and readability.

Ah! alright. Let’s proceed.

Use the extract method in following cases —

When your class contains a long method.

A long method does more than one thing and it is not considered as cohesive. The method more than 10 lines could be considered the as long method.

See this example of a long method, It is doing more than one thing.

Setting up GST rates, item/category mapping, accepting user inputs, calculation and so on. 

A long method is considered a code smell. 

Now see the refactored version of the above long method.

It is divided into small, cohesive, fine-grained methods which are doing one and only one thing.


When you favor a comment to express the intent of the code.

Before

 ...
// Parse input and convert it into Document
var xDocument = XDocument.Parse(input);
var document = new Document
{
   Title = xDocument.Root.Element("title").Value,
   Text = xDocument.Root.Element("text").Value
};
...

Here let’s get rid of comment [Parse input and convert it into Document]. 

After

...
var doc = ParseInput(input);
var serializedDoc = JsonConvert.SerializeObject(doc);
...
private Document ParseInput(string input)
{
    var xDocument = XDocument.Parse(input);
    var document = new Document
    {
        Title = xDocument.Root.Element("title").Value,
        Text = xDocument.Root.Element("text").Value
    };
    return document;
}

When the extract method helps you to improve readability.

Do you know that people extract method for a single line too? Because it adds to the readability of the code. Sometimes a statement may be difficult to interpret. In that case, you could use the extract method to convey intent instead of taking the aid of comment.


When there is a code duplication or copy-paste.

Consider below example, it is formatting date and code is duplicated. Perhaps, lines are copied and pasted.

Before

    var formattedStartDate = startDate.ToString("dd MMMM yyyy");
    var formattedEndDate   = endDate.ToString("dd MMMM yyyy");

As soon as you see copy and paste of lines of code then go for an extract method refactoring even if it is a small portion of code.

After

    var formattedStartDate = FormatDate(startDate);
    var formattedEndDate  = FormatDate(endDate);

public string FormatDate(DateTime date)
{
   return date.ToString("dd MMMM yyyy");
}

The advantage

  • Code becomes more readable.
  • Fine-grained methods make code easier to understand.
  • You can easily plug-in and plug out the implementation for some routines.
  • When your method becomes cohesive, you can easily spot the bugs in the code.
  • Your calling method reads more like a sentence.

Points to Ponder —

  • Remember, keep the method short, well-named, and cohesive to get more benefits out of it.
  • Your calling method should read more like sentences.
  • When extracting a method, a developer should think about the cohesiveness of the class. should ask a question to oneself: Does the extracted method really belong to this class? If Not, then move it to the appropriate class that should perform that operation.
  • Small methods really work only when you have good names.
  • Don’t just extract method if you can’t give the meaningful name.

Extract method only if you can give an intuitive name.

Authentication and authorization

 

Authentication:

I don’t know who you are, so, you are not allowed to enter the premises.

Authorization:

I know who you are, you are allowed to enter the premises. However, you do not belong to the accounting department hence you are not allowed to perform any action like accessing resources in this section of the premises.

Authorization is all about what you can do.

 

When you work with any web technologies, be it server-side UI generation or serving API. They always provide you interceptors (The components who intercept the HTTP request) to perform these checks.

These interceptors may be called as HttpModules, Middleware and so on.

In ASP.NET, we could achieve it using pluggable HTTP modules or C# attributes, and so on.

In ASP.NET MVC or WebAPI, we could authenticate or authorize request using Authentication and Authorization filters at the controller action level, controller level or at the global level.

 

Don’t forget to return below HTTP status code from web API if a request fails to authenticate or authorize.

401 UNAUTHORIZED

Don’t confuse with unauthorized. It says valid authentication credentials for the target resource are missing, Authentication failed.

403 FORBIDDEN

It means the server understood the request but refuses to authorize it.

Developer Professionalism : Take a stand

Few weeks ago, I was travelling to my hometown by a bus. I reached the pick-up point at scheduled time, but when I arrived, I found that the bus was late.

Finally after a wait of 2 hours, the bus arrived and the driver found himself in the middle of many angry passengers who were also waiting for the bus. After a while, I patiently asked the driver, “What was the problem?”. To which he replied, “The bus is having problems since last 4-5 days. I told the management that we need at-least 2-3 days to fix the bus, but they are not ready to listen. They are insisting to run the bus by doing a quick-fix for the time being.” I again asked him, ” Are you sure it won’t fail again?”. He replied, “We’re not sure, let’s pray that the bus does not fail.”

It was an overnight journey, I started thinking, why is the crew taking such a risk of using a bus they are not confident of. There were kids, old people on that bus. What-if it fails in middle of nowhere?

How many of us have encountered such a situation before in our own professional lives?

Have you ever been asked to ship a low quality quick fix, so that the software can be shipped into production quickly?

Have you ever been pressurized to develop a piece of code in short time, thereby giving you less time and opportunity to produce a good work?

I have been in such situations too and to be honest, I’ve even done that. I’ve succumbed to pressures. But is that the right thing to do?

People from these professions, such as doctors, construction engineers have an obligation towards the society and that obligation is to protect human lives first.

Software these days, is no different. Software is everywhere. It’s being used to suggest what medication a patient should get, it’s driving cars for you, it’s even bringing you from top floor to the ground floor of the building you live in. It’s omnipresent.

And the onus to ensure that it works as expected, is on us. People have lost lives, due to bugs in software, it’s as real as it gets. Developers these days, are now being held accountable for the work they produce.

So if you are not sure, if you’re code will as expected, if you are not sure, you’ve covered all edge cases, if you are not sure that the quality is up-to the mark, learn to say NO, take a stand. (But remember, when you do so, do it with a proper justification too.)

Don’t be too clever

A few days ago, I along with my friend went to the restaurant. When I went to use a washroom, I found these symbols on the doors.

I realized the humor of the designer and then I went to the Male washroom. However, I observed that other people who don’t understand the humor, having difficulty to understand the correct washroom. They had to ask staff for help. Hmm! That’s not that user-friendly.

Similarly, people try to be too clever while writing the code.

Please see the above code snippet. Do you understand the intent of BombDetector.Detect? Original author must have tried to use his humor while writing the code.

However, the maintenance developer may not understand the humor behind it and he would feel helpless to understand the intent.

The original author was checking the value of the input argument and throwing the exception if a value of an argument is null.

Above snippet could have been kept simple.


Try to keep your code as simple as possible so that everyone could easily understand it and easily work with it.

Start slowly to finish fast

“In programming, the hard part isn’t solving problems, but deciding what problems to solve.” – Paul Graham

I am fortunate enough to work with new, genius, competitive developers who have fresh perspectives. They often talk about faster algorithms, data structures, new-generation technologies, and buzzwords in the software industries. They are eager, motivated and wanted to change the world!

However, I did not hear from them about problem-solving using object-oriented analysis and design.

Some people try to solve the problem by directly jumping into programming solution without doing an analysis. They believe in trial and error methods. It’s like solving problems without knowing what problems to solve.

The well-proven OOAD techniques are there for decades, It’s a very beneficial technique for problem-solving. They will help you to know what problems to solve.

We should focus on what problems to solve rather than just writing the code.

IMO, we should start slowly to finish fast. What I mean here is, we have a problem at hand, divide it into three parts: Analysis, Design, and Programming.

These three are related terms.

The object-oriented analysis is meant for understanding the customer problem. Write use cases to capture what is needed and what is not. You can write lightweight use cases. Thus, you’ll focus on what is needed than trial and errors.

Benefits of writing use cases!

The next step would be the object-oriented design which emphasizes on designing the conceptual models i.e. classes to achieve the various use cases.

This classes will have attributes and behaviors. They interact with each other to solve the problem.

Try using outside in approach, class diagrams, sequence diagrams. You could use the whiteboard to evolve your conceptual design that tries to solve the customer problem.

Object-oriented thinking, the big picture!

Then comes the programming phase. Now you know “what part” of the problem and conceptual models, you can focus on how part i.e. coding.

The good analysis and design would help you to understand problems to solve, prepare good conceptual models, that intern leads you to good programming solution for the problem at hand.

Remember, don’t directly start coding without understanding the problem to solve.

Instead, use object-oriented analysis and design.

Start slowly to finish fast.