This is part of a brief series on Good Habits For New Java Programmers.
Use meaningful names for variables
A meaningful name for a variable is one that tells us what the variable represents or what it's used for or how it's used in the program, and does not use too much shorthand. Let's dive in.
Don't name variables after the type they store
There's a tendency to use a letter or name for a variable that simply matches the type of the variable.
Consider this:
double d;
The name d
is not meaningful. It hints that the variable stores a double
, but it doesn't tell me what this double
is going to be used for or what it's storing. Likewise, array
and doubles
in
double[] array = new double[10];
double[] doubles = new double[10];
are not examples of meaningful names. The first name, array
, conveys to me that the variable stores an Array, and the second name, doubles
, conveys that variable stores an Array of double
s. But knowing the types are not enough to know what the variables do in our program. Neither tells me why I'm going to be storing an array of double
s or how this Array is going to be used in the program.
Let's imagine that these double
s are meant to store prices. Then these would be more meaningful names:
double price;
double[] prices = new double[10];
You should get even more specific, if that makes sense:
double coffeePrice;
double[] coffeePrices = new double[10];
Don't over abbreviate your variable names
There's a tendency to needlessly abbreviate otherwise meaningful names. Here are some examples someone might use instead of double sellerCost;
double sc;
double sCost;
double selCost;
Those are in increasing order from worst to better (though none great), as the increased number of letters gives more hints as to what the abbreviation is for. Don't force yourself or your readers to guess how to interpret a vanity license plate style abbreviation -- just make it obvious:
double sellerCost;
It doesn't cost you much: you type a few extra letters the first time, and then your IDE/programming environment will give you autocomplete suggestions for the next time you want to refer to that identifier. And it dramatically improves the readability and maintainability of the code. Not just for me, the reader, but for you: when reading an expression such as sc - bp
you will have to translate sc
into "seller cost" and bp
into "buyer price" to understand what the expression is doing. That translation adds a mental tax. You don't have to pay that tax when reading sellerCost - buyerPrice
.
Sure, a name like purchPrice
for a purchase price isn't that hard to expand in your head to "purchase price", but why not just write it out in full to save us all the mental step? purchasePrice
is a better name for your variable than purchPrice
, even if purchPrice
isn't terrible.
Don't tack on numeric values to variable names to distinguish them
Sometimes you need to represent two of a similar kind of value: maybe you have two kinds of prices, one for the cost of something to you, the seller, and one for the sales price that the buyer pays. Use meaningful names to distinguish your variables for them. costPrice
and salesPrice
, for example. Or maybe sellerCost
and buyerPrice
. You get to think of what names make sense, but you have to put some effort into it.
Don't use price1
and price2
. The 1
and the 2
don't tell you or me (the reader of your code) anything meaningful that helps us to remember or keep track of the difference in what the variables represent. Will you remember as your program expands which of price1
or price2
holds the cost to the seller or the cost to the buyer? Later when you read a line of code
double profit = price1 - price2;
will you be able to see easily if that's a mistake and should be the other way around? Should it be
double profit = price2 - price1;
?
It's much easier to understand your program if instead, you had
double profit = buyerPrice - sellerCost;
That will help you make sure your programs are correct, help your readers of your code help you improve it, and make it easier to build on your program later: if you have to come back and add more functionality later -- let's say sales tax -- it'll be much easier to know which of those variables you should be applying the sales tax to.
There are counterexamples (aren't there always?), but in general, you should ban the usage of number suffixes on your identifiers: don't tack on a 1
or a 2
, etc. onto any identifier.
Use meaningful names for methods, classes, parameters, and everywhere else, too.
A method named doIt()
doesn't have a helpful name. Do what? What happens when you add another method? How will you distinguish them? Perhaps with a method named doIt2()
? Which one does what?
That doIt
example may seem far-fetched, but it's not uncommon to see students create a method getPrice()
(much more meaningful than doIt()
, for sure!) and then need another method to do something similar, and create a getPrice2()
. Instead, it would be better to have methods named, for example, getSellerCost()
and getBuyerPrice()
. Now you know and I know what these methods should do.
The same sort of thing applies to class names or wherever you come up with names in your programs. If you see a method signature
private void getProfit(double d1, double d2)
do you know which double
is intended to hold seller's cost and which is intended to hold the buyer's price? How about
private void getProfit(double sellerCost, double buyerPrice)
? That makes it clear.
I admit it: there are exceptions
Okay, so, it's true that sometimes, the language for the subject matter we're talking about naturally uses abbreviated terms or single letters for things. For example, when we talk about points on a plane, we use x and y to represent the coordinates of that point. In that case, it does make sense to have variables named x
and y
: e.g.
public class Point {
float x;
float y;
public Point(float x, float y) {
this.x = x;
this.y = y;
}
}
And it is convention to use i
, j
, k
for iterators in for loops. E.g.
for (int i = 0; i < 10; ++i) {
// Your code here
}
If there's a natural abbreviation that does not require work to decipher, it's okay to use that: String ceoName;
is perfectly readable and much more natural than String chiefExecutiveOfficerName;
And sometimes, you really are writing a generic function that takes two of a primitive type, say, and it makes sense to write something like:
public void reverse(String string)
or
public int sum(int num1, int num2)
You can go too far
My experience is that there's little danger here for new programmers, but it's also true that a name like itemPriceIncludingAllTaxesAndDiscounts
is a bit of a mouthful and takes up a lot of room on a line. Naming is hard and involves judgement, but in general, err towards more informative names than less informative ones.
Sometimes examples you find do not use meaningful names
Sometimes the texts you use or examples you look up on the web will not do as I'm saying.
That's unfortunate, since it means some of your authorities on how to write code will be tacitly contradicting my advice. And it's common (advisable, even!) to copy and paste examples to help you get started on some piece of code, and it's easy to miss the need to go back and clean up the example. But do go back and clean up what you copied to use meaningful names.
Perhaps there's some good fortune in the fact that you'll run across plenty of code that doesn't do as I say, though. I'm hoping you'll realize that when you read that code, you find it harder to read and harder to learn from than you would have had your source used more meaningful names. Maybe that will help this topic seem like sound advice, rather than just a set of rules to follow.
If you're here, you might also want to read Naming Conventions.
Top comments (0)