28
Clean Code Part 1: Meaningful Names
Naming variables, functions, classes, arguments, and packages is an art not everyone understands. Those who understand, live a technical debt-free life. But few simple pointers can help you reach this goal. While most of these will sound obvious but are not completely implemented by a lot of developers. Read ahead to crack the code for writing meaningful names.
Choosing good names takes time but saves more than it takes.
The names of variables, functions, classes should answer three broad questions:
var d; //does not reveal anything
var daysSinceCreation; // clearly reveals what it stores
var isModalOpen; // depicts the variable is a boolean
const getUserID; // denotes a function or task
Hence, focus on the simplicity of the code rather than simplicity. If a variable requires a comment, it does not reveals its intent well.
Avoid names which leave false clues which might obscure the meaning of code. Treat it as an honourable human, it should say what it means and mean what it says.
AccountList
unless it is a list.isAccountInformationOfUserRequired
and
isAccountInformationOfAdminRequired
.Number-series naming like a1, a2, ...., an makes the code non-informative and does not reveals anything about the intention.
Another avoidable typing of naming is using noise words. Words like variable, NameString, Customer, does not reveal anything and so should be avoided.
Use words that are pronounceable so that others can use it for communication. This will enable better collaboration because "Programming is a Social Activity".
Imagine someone calling you to fix the bug and mentions using the function getmddh which gets month, date, day and hour for the post. Saying "get-M-D-D-H" is both frustrating and confusing, so rather just call it getPostTimeStamp.
Similarly names should be searchable. Single or double letter names are hard to search in a codebase. In this case Ctrl+Shift+F will no longer be at rescue and is such a bade case for giving meaningful names.
Names should be such that it reveals the role of the variable, this specially is very important in languages like JavaScript everything is either a var, const or let.
Sometimes variable names require additional data to give context to generic variable names like firstName, LastName, city, zipcode etc. In such a case adding a prefix like addrfirstName and addrLastName will denote it being a part of a larger Address class.
Quoting from the book,
Any fool can write code a computer can understand, but it takes a good programmer to write code that humans can understand.
Head over to Part 2 of the series.
28