loading...
Cover image for A function’s intent should be revealed by its name

A function’s intent should be revealed by its name

le0nidas profile image le0nidas ・1 min read

And a good way to know if it doesn’t is to read it where it gets used. If, after reading it, you have questions then something is wrong with the name.

A good example is this code that I run into:

if (handleClickItem(customer)) {
    return;
}

When I read this piece of code the very first thing that popped into my head was

How does the click gets handled?!

To figure that out I had to step into the function’s body and start reading it in order to understand what it does and when. It broke my flow and made me change context.

Turned out that this particular function, depending on the customer’s type, opens the contact’s screen and returns true or simply returns false. Having read something like:

if (openContactsScreenWhenCustomerIsCompany(customer)) {
    return;
}

would have been enough for me to simply keep reading and never look back.

(cross post from: le0nidas.gr)
(image from: Patrick Perkins @ unsplash)

Discussion

pic
Editor guide
Collapse
aeddi13 profile image
Patrick Decker

Good article. The correct naming of variables and methods is one of the most important and fundamental parts of programming that many developers still get wrong.

In some cases however, it is not possible to name the method correct for every place where it is used. In these cases adding a variable with the correct name before the if statement will increase the readability a lot.

bool openContactsScreenWhenCustomerIsCompany = handleClickItem(customer);

if (openContactsScreenWhenCustomerIsCompany) {
return;
}

Collapse
le0nidas profile image
le0nidas Author

That's true. Thank you for pointing it out :)