TLDR Clean Code, Meaningful Names

Heshan P.
AMA Technology Blog
8 min readMar 13, 2023

I learned to code through school, online courses, and projects. How “clean” my code was not something that crossed my mind. With so many languages, frameworks, tools, libraries, and design patterns to learn, it didn’t seem like a priority. My focus was on getting good grades or finishing my projects. Not at the beginning at least. Soon, I realized that it's a really important skill, especially when you work with others on medium-large projects. I am going to read the famous “Clean Code” by Robert C. Martin and write a series of TLDR versions of what I found interesting and relevant. I hate reading, so this is also my accountability system.

Some of these concepts might be obvious for experienced developers but might still be worth a revisit.

What Is “Clean Code” and Why Should We Care?

Photo by Tyson Moultrie on Unsplash

“Clean Code” could mean a million different things, depending on the person and their experience, attitudes, and priorities. Here are some interesting takes:

Elegant and Efficient. The Logic should be straightforward to make it hard for bugs to hide.
— Bjarne Stroustrup
(inventor of C++)

Like well-written prose. Never Obscures the designer’s intent.
— Grady Brooch
(author and developed the UML)

Can be read and enhanced by a developer other than its original author.
— Dave Thomas
(founder of OTI which contributed to Eclipse technology, and other tech)

Always looks like it was written by someone who cares. There is nothing obvious you can do to make it better.
— Michael Feathers
(author of Working Effectively with Legacy Code)

In my view, it's about how the code we write can stand the challenges of efficient development, maintenance, and collaboration.

  • Efficiency? Cleaner code makes it easy to modify, debug, and extend, even as the software evolves, grows, and extends.
  • Maintenance? We will always have bugs to deal with, and improvements to make. Cleaner code makes that easy.
  • Collaboration? Most of our work is done by teams of developers. Clean code helps us communicate our intentions to others who may have no context. Clear communication is key to effective collaboration.

Why Should We Care?

It’s because owning a mess is scary. It takes hours to figure out what’s going on when you’re fixing a bug. It’s painful to add a feature that isn’t duplicating or rewriting existing code. When you change something, it breaks other parts. On top of the massive waste of time, it can be frustrating and nerve-wracking. This doesn’t bring out the best in any of us. This is what we should aim to avoid. As Bob (Robert C. Martin) puts it: “it's not just cost-effective; it’s a matter of professional survival”.

DUH, Clean Code is good, and messy code is bad, then why do we have bad code?

There can be many reasons. Usually, it's deadlines, changing requirements, poor architecture, managers, customers, designers, limitations in technology used, and so on… “but the fault, dear Dilbert, is not in our stars, but in ourselves” says Uncle Bob. It's usually our own fault. Ultimately, you are the subject matter expert on the problem you solved (or tried to solve), and you decide how you use code to solve it.

Disclaimer: We can’t let perfection stand in the way of progress, but we can get close to it. We have priorities, deadlines, and others depending on us. There is always refactoring and continuous improvements — the least we can do is to put some thought into it and look for the most obvious improvements we can make before we decide it’s good enough.

Alright, now that Clean Code and why it matters makes sense, let's look at some concepts.

Meaningful Names

Photo by Einar H. Reynis on Unsplash

Names? really? I thought the key concepts would be something to do with design patterns, or something more technical. Without good names, everything else falls apart. Names are everywhere we look. Usually associated with a keyword like let, const, class, function, method, import, export, type, object, column, etc. we use it to help ourselves and the compiler keep track of bits of information.

How Can We Come Up with Better Names?

It's about reducing Cognitive Load. Cognitive Load is like our working memory, similar to RAM in a computer. Poor naming can take a lot of “RAM”. Names shouldn’t make you look back and second guess your understanding. We really should save our RAM to spend it doing something more useful.

Reveal Intent

Names for variables, classes, functions, etc. are one of the biggest tools in writing cleaner code. Besides pointing at data, it can easily explain what things are meant for.

I am happy to say that I was not able to find any obviously poor names in our codebase, so I am borrowing some from the book.

let m; //best to avoid single letters, except in loops

const DIW = 7; // not clear at all
const DAYS_IN_WEEK = 7;

let cList[]; //what is c?? and 'list' can be deceptive(list vs arrays)
let customers[];// this is much better

Another way to show intention is by using nouns and verbs appropriately within names.

  • Nouns for Classes, Objects, and other Entities. Like: Customer, Account
  • Verbs for Functions and Methods. i.e., cancelSubscription, calculateAccountBalance

Examples below are some closely related names. There are subtle differences, and the names do a pretty good job of revealing intent:

//FYI: "Membership" appears 4852 times in 383 files in our repo

// 👇this avoids any confusion by detailing the intention
type MembershipRequest;

// 👇difference vs 'MembershipRequest' is clear without even looking at code
type MembershipRequestWithHeaders;

// 👇reveals nuances to avoid misuse
type MembershipRequestWithAuthHeaders;

// 👇long but necessary
function getInitialMembershipInfoWithMembership();

// 👇reveals intent without effort (vs reading the return type)
function getEndOfTermString();

Using acronyms and short-form phrases can hurt in the long run. For instance, cancelSub vs cancelSubscription, getAcctBalance vs getAccountBalance. The time it saves us writing is minimal, but the clarity of the naming can hurt our Cognitive Load even if it's a little bit, and it can quickly add up to a confusing mess. Oh, and it can hurt searchability…

Name for Searchability

This is not something I thought much of. Clear names are easy to look up. Modern editors like VSCode are powerful tools that can search 1000s of files in milliseconds. It even tries to help you with auto-fills and suggestions. Searchable names help code reuse by allowing someone to search for helper functions, classes, and variables. Clear names like formatAgentName(),getCustomerByLastName(), DEFAULT_USER_NAME can help save significant development time.

Avoiding empty words like helper can also help sharpen our searchability. Functions are already helpers, so adding “helper” doesn’t add value. If you are having a hard time with words like helper or and, you may be violating the single-responsibility principle. If that’s the case, it's best to take another look at the function instead of playing scrabble with its name.

Photo by Brett Jordan on Unsplash

Consistency is key for searchability. If the database uses something like membership_number, we should use membership_number or membershipNumber whenever possible. Names like memNum, or even memberNumber may cause confusion.

Avoid Acronyms Unless It’s Obvious to Your Audience

Acronyms can be a good tool, but you have to consider your audience. If you are on the fence about it, it’s best avoided. For example, anyone in AMA knows what AMA stands for — Alberta Motor Association. We also know phrases like RSA(Roadside Assistance) and M2(fancy name for Membership Simplification). This is something familiar to the team and in most cases, it’s fine with our audience. However, we should consider external vendors and other stakeholders like contractors, data analysts, etc. What are the odds that this would confuse them? if it's fairly high, reconsider using it.

There are also acronyms like API and GUID that most of us reading the code would be familiar with, so this gets the green flag.

Some examples to illustrate:

//BAD❌
getSESResponse()
// 👆 could this be Amazon SES - Simple E-mail Service? OR
// is it related to SubscriptionEnrollmentSubscription

const EH_ERRORS; //EH = Event History
// 👆 not obvious enough for it to replace EVENT_HISTORY_ERRORS

//OK - in most cases
type TransferGCEventBody; // vs TransferGiftCardsEventBody
type APIGatewayProxyEventV2; // vs ApplicationProgrammingInterfaceGatewayProxyEventV2
let ESBTransactionGUID // our audience would know what this is, so its ok to use

Don’t Mislead

If your function uses a phrase like get or set, it should return something or set/update a value. is customerList[]really a List? or is it an array of Customer objects?

Let's look at an example:

const validateName = (firstName: string, lastName: string) => {
// logic to check for special character, length, etc.
// returns cleaned version of the name
return { validName};
};

Is this actually validating something? not really. It returns a cleaned-up version of what was sent. getCleanedUpCardNameswould be more accurate.

Context

Context can change the meaning of a name. The word state can mean condition of something (similar to status) like processed, in progress, or complete. It can also mean state in a US address like California or Texas; and it could also mean state in the context of React where state plays a fundamental role in the framework. So, what does it mean when you see something like getState or setState?

This can be clarified by using prefixes, classes, or typing. Address.State using typing/enums or classes or simply naming it addressState is much clearer.

Don’t Be Cute

Phrases like kill() and whack() are best avoided along with puns and inside jokes. Our goal is to make it easy to understand with very little Cognitive Load on the reader. Cute-ness can backfire in many cases. Culture, people, and context can change — and these names might age poorly.

I get it, some of this can come off as nitpicky. Meaningful names lay the foundation to clean code, so it deserves some nitpicking.

Coming Soon…
Functions, Comments, Error Handling, Unit Tests, and more

Who Are You and Why Are You Doing This?

You will probably be able to tell very soon that I am very much inexperienced in software development and blogging. This is my attempt to condense some information that can help fellow noobies, and maybe refresh the perspectives of some experienced devs. HOWEVER, the more selfish reason is that I want to read and learn more about Clean Code (not a big fan of reading). Hopefully, writing this series of blogs will help me learn better, stay on track, and maybe help someone else.

References
R. C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship. Prentice Hall, 2009.

--

--