Sure, well-named variables and functions are important in all programming languages. But when is a name good enough? And when is it especially critical? I just received an interesting comment about my new Clean Code course on Pluralsight. The commenter felt that “Get” is a fine method name and used the example of
person.Get(personId). This example reads clearly enough, but there’s three reasons to question such a short function name, particularly when working in a dynamic language.
1. Statically Typed Languages Help Convey Intent
Note the two additional pieces of fidelity that you pick up in C#:
- Parameter type – You can see a personId of type int is the argument
- Return type – It’s clear the method returns a person. There’s no need to read the body of the method to know this in C#.
These two pieces of information help clarify the intent of the function. Thus, you can certainly get away with more terse method names in statically typed languages.
2. What about the future?
There’s a second issue with a short method name like “Get”. What happens later when there are multiple ways to get a person by the same datatype? Imagine we create a new function that gets a user by phone number or Social Security Number. (insert gasps here). At this point the method name “Get” becomes risky business. People may pass it a phone number, not realizing it expects a personId. You’d thus be likely to rename “Get” to “GetByPersonId” at that time to resolve the ambiguity caused by the short function name. And this leads to the third issue.
3. The Risky Rename
One could certainly argue that’s GetByPersonId is what the method should’ve been named in the first place – especially in a dynamic language. And this leads to the final reason naming matters more in dynamic languages: When you decide to rename variables and functions later, statically typed languages allow you to “lean on the compiler” for safety. This term comes from Michael Feathers’ book “Working Effectively with Legacy Code“.
Leaning on the compiler involves two steps:
- Altering a declaration to cause compile errors
- Navigating to those errors and making changes
You can lean on the compiler to make structural changes to your program.
You have no such crutch in a dynamic language and thus introduce greater risk anytime you rename. This is also why a robust testing suite is particularly critical in dynamic languages – it helps fill in for simple bad reference issues that a compiler would’ve caught in a statically typed language.
The bottom line is we live in a world of intellisense, high resolutions, and dirt cheap storage. So when torn on which name to choose, clean coders should err on the side of clarity rather than brevity. And in a dynamic language, this principle is all the more important.
There’s much more to be said on the topic of variable and function naming. To learn more, check out “Clean Code: Writing Code for Humans” at the link below and chime in on Hacker News.