This is the second post in the series ‘Introduction to Professional Programming Concepts’. The first post was What is Dependency Injection?
In programming, appropriate naming of everything is extremely important to being able to read and understand code. This applies whether you’re reading code that someone else wrote years ago, and even to code you wrote last month! With a cursory understanding of code structure and flow control, anyone should be able to read and understand your code – a person on your team, a QA engineer, even a non-technical manager. With proper naming, understanding code is not a problem.
Consider the following function:
When you’re stuck trying to figure out what a function like this is supposed to do, it can be a tedious and painful process. The function’s name is fairly cryptic, and parameter names have no meaning whatsoever. If you see code written like this, it means that the developer either didn’t care enough to take the time to make their code self-documenting, or they were simply unaware of its importance in professional software development. What if the function looked more like this?
Now, the meaning of the arguments and the purpose of the function become clear. It even highlights a possible bug – probably the customer is eligible if their number of months is equal to the minimum required! Test-driven development is great, but we just discovered a bug just by naming things properly!
This concept applies all the way through the software stack – from parameters and variable names, all the way up to class names and module or library names. I’m not going to take the hard line here that some people do – that all comments are signs of bad code – but it is true that the vast majority of comments can be replaced and improved by using proper naming to make the code self-documenting. Here are some guidelines I like to follow when it comes to naming things in code:
- Never use one-letter parameter names, except as an iterator (i) or as a lambda input parameter
- Never be afraid to give something a longer name if it helps with understanding its purpose
- Class names should be nouns, method names should be verbs
- If you are working on poorly-named code, rename each piece as you understand its purpose
I hear that Pluralsight has a new Clean Code course, and it has a naming module! I will be watching that at my earliest opportunity, and adding to this post based on what I learn. As with all my posts, this is only my opinion. I can (and will!) change it when my experience shows me where I’m incorrect.
Have other code naming tips or guidelines? Share them in the comments!Leave the first comment ▶