Main menu

Pages

Clean Code - T2- Packing Information into Names

 

informative names-clean code

Whether you’re naming a variable, a function, or a class, a lot of the same principles apply.We like to think of a name as a tiny comment. Even though there isn’t much room, you can convey a lot of information by choosing a good name.
 
KEY IDEA 
Pack information into your names.

1-Choose Specific Words

Part of “packing information into names” is choosing words that are very specific and avoiding“empty” words.For example, the word “get” is very unspecific, as in this example: 

def GetPage(url): ... 

The word “get” doesn’t really say much. Does this method get a page from a local cache, froma database, or from the Internet? If it’s from the Internet, a more specific name might be 

FetchPage() or DownloadPage(). 

As another example, suppose you have some sort of Thread class:

class Thread { 

void Stop(); 

 ...}; 

The name Stop() is okay, but depending on what exactly it does, there might be a more specific name. For instance, you might call it Kill() instead, if it’s a heavyweight operation that can’t be undone. Or you might call it Pause(), if there is a way to Resume() it. 

2-It’s better to be clear and precise than to be cute. 

use words that are specific and precise to describe your variables and methods, Example:
void send(){
}  
not till us what this method send and by who and to who it's better to rename it like
deliver(){}, dispatch(){} , sendByEmail(){}.
 

 3-Avoid Generic Names Like tmp and retval

Names like tmp, retval, and foo means “I can’t think of a name.” Instead of using an empty name like this, pick a name that describes the entity’s value or purpose. 

Example:

usersTotalAges(){

let retValue  = 0;

for(let user of users){

retValue+=user.age;

return retValue;

retValue is used to calculate sum of users ages but it's not more descriptive let's use another good variable name,

usersTotalAges(){

let usersTotalAges  = 0;

for(let user of users){

usersTotalAges+=user.age;

return usersTotalAges;

}

usersTotalAges is a more descriptive and till us what data that this variable hold. 


There are, however, some cases where generic names do carry meaning. Let’s take a look at when it makes sense to use them.

Consider the classic case of swapping two variables: 

if (right < left) {

 tmp = right; 

 right = left; 

 left = tmp; 

}

 In cases like these, the name tmp is perfectly fine. The variable’s sole purpose is temporary storage, with a lifetime of only a few lines. The name tmp conveys specific meaning to the reader—that this variable has no other duties.

3-2 Loop Iterators 

Names like i, j, iter, and it are commonly used as indices and loop iterators. Even thoughthese names are generic, they’re understood to mean “I am an iterator.” (In fact, if you usedone of these names for some other purpose, it would be confusing—so don’t do that!) 

reactions

Comments