Home Naming
Use descriptive names
Be descriptive and succinct when naming variables, fields or methods. You should almost never use a single-letter name or an overly long name.
There are a few exceptions to this rule. One notable exception is loop variables for
for
loops. You may use single-letter variable such as i
or
j
. Expand for more details.
Variable and method names can be a very powerful tool for enhancing readability. Picking good names can make even the most complex and confusing code understandable to beginners.
If we distill naming down to the basics, we arrive at the following rules:
-
Give variables and methods names related to what it's supposed to represent or do, not just its type.
Try and pick names that add context to your code. For example, instead of naming a method
checkInt
, call itcheckIfPrime
instead. -
Avoid single-letter names, and too-long names.
For example, instead of calling a variable
x
ortheNewStringThatIAmAppendingDataTo
, call itresult
instead. -
Avoid variables with similar yet generic names.
For example, you should avoid giving variables names like
temp1
,temp2
,temp3
, etc. Try and be purposeful and specific about naming. What does each variable represent? What exactly does it contain? -
Prefer using verb or verb clauses as names for methods, and nouns or noun clauses for variables and classes.
This convention reflects the fundamental difference between methods and variables. Methods do; variables are.
-
Note: You should usually avoid single-letter variable names, but there are a few exceptions to this rule:
- Loop counters in for loops, such as
i
,j
, andk
. - When working with scientific formulae, such as
c = Math.sqrt(a * a + b * b)
. You will almost never encounter this case in CSE 142 and 143. - When the variable has no inherent meaning beyond its type, such as with the Graphics object, the Random object, and with many exam questions. We will explicitly inform you when you run into this case.
- Loop counters in for loops, such as
What happens if we don't follow these rules? Consider the following code which violates nearly every rule listed above:
public List<String> get(Map<String, Integer> map, String strA) { int num = map.get(strA); int c = 0; List<String> r = new ArrayList<String>(); for (String n : map) { if (!n.equals(strA)) { int num2 = map.get(n); if (num == num2) { r.add(n); } } } return r; }
Can you tell what this code is doing? No! If you're in CSE 142, you probably wouldn't be able to understand most of it, given that this code sample uses several 143 concepts. If you're in CSE 143, you might be able to understand what it's doing if you sat down and traced through it, but you wouldn't be able to intuitively understand what this method was intended to do in the first place.
Certainly, we could clarify the intent of the code by including inline comments, but we can do better.
For example, what if I took that above method and renamed all of my methods and variables to the following?
public static List<String> getMyRoommates( Map<String, Integer> nameToRoomNumber, String myName) { int myRoomNumber = nameToRoomNumber.get(myName); List<String> myRoommates = new List<String>(); for (String name : nameToRoomNumber) { if (!name.equals(myName)) { int theirRoomNumber = nameToRoomNumber.get(name); if (myRoomNumber == theirRoomNumber) { myRoommates.add(name); } } } return myRoommates; }
Suddenly, it's much more understandable what exactly this method is doing.
If you're in CSE 142, you still won't understand what things like List
s
or Map
s are, but at least you now understand that this method will in some
way get all your roommates and have some sense of what each parameter is.
The variable and method names have added a valuable layer of context that allows you to understand the meaning and intent of this code.
Now, while in 90% percent of the cases you should try and write code like this, it's worth talking about the three main exceptions to this rule:
- Loop counters in for loops, such as
i
,j
, andk
. - When the variable has no inherent meaning beyond its type, such as with the Graphics object, the Random object, and with many exam questions. We will explicitly inform you when you run into this case.
- When working with scientific or mathematical formula where single-letter variable names are the norm.
The first exception is with loop counter variable names, such as i
,
j
, and k
. It's ok and encouraged to like this:
public static void printSquare(int size) { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { System.out.print("*"); } System.out.println(); } }
This is partially because loop counters don't really need context, and also because
using the variables i
, j
, and k
as loop counters
is a convention all programmers will understand, both inside and outside UW.
Of course, you're also free to pick different variable names if you want. For example, if you want to be more explicit, you could rewrite the above code sample as:
public static void printSquare(int size) { for (int lineCount = 0; lineCount < size; lineCount++) { for (int charCount = 0; charCount < size; charCount++) { System.out.print("*"); } System.out.println(); } }
And in fact, if you're still trying to get the hang of for loops, it may be a good idea to write code in this second, more verbose style. That way, it'll be easier for you to keep track of which variable represents what.
The second exception is when you're writing code where there is literally no context
for you to work with. For example, take the Graphics
and Random
objects. There's really no inherent "meaning" behind those objects in the same way the
variables and methods had "meaning" in the getRoommates
example. You could
declare your variable as Graphics graphics = new Graphics()
if you really
wanted, but it is a bit tiring, so we're ok with single-letter variable names here.
Another example of this is with many exam questions. For example, in CSE 143 a common
midterm question is to ask you to take some stacks and queues and manipulate them.
However, there's no inherent meaning behind those stacks and queues. We're only
interested in the data structure itself. As a result, we'd be ok with you naming those
variables s
and q
.
Because it's often difficult to determine when this second exception applies, we will explicitly tell you when it's ok to use single-letter variable names. If we don't mention anything, you should always assume that full variable names are required.
The final reason is with when working with scientific and mathematical formula, where single-letter variable names are so standard that longer names are unnecessary. You will almost never run into this case while taking CSE 142 and 143.
The only case I can think of is using x
and y
for representing
X and Y coordinates while working with graphics-related code. Note that quantities like
"width" and "height" should not be abbreviated to w
and h
, since
not everybody will recognize that abbreviation.
Follow Java naming conventions
Names must follow standard Java naming conventions. Variables, methods, and fields should
be in lowerCamelCase
, classes should be in UpperCamelCase
, and
constants should be in SCREAMING_CASE
.
Every programming language has a slightly different set of conventions on how to name variables, methods, and classes. Some companies and organizations will then have their own modified set of conventions and rules.
We are learning Java, so we will follow standard Java conventions, which is followed by most Java programmers in industry.
-
Variables, methods, and fields should in "camelCase" – each word starts with an uppercase, except the first word.
Examples of good variable, method, and field names include
record
,totalGuesses
,findBiggestFamily
,name
, andnumberOfGuesses
. -
Classes should be in "CamelCase" – each word starts with an uppercase and is placed together with no underscores.
Examples include
String
,Scanner
,Critter
, andLetterInventory
. -
Constants should be in "SCREAMING_CASE" -- each word is completely capitalized and separated by an underscore.
Examples include
DEFAULT_CAPACITY
,INITIAL_NAME
, andHEIGHT
.
You may be curious as to why these specific conventions were chosen.
In Java, we have several different kinds of "things". We have variables, methods, constants, fields, and classes. In order to avoid getting confused between them, we want to stick by some sort of naming convention so that other programmers can more easily understand what something is supposed to be. However, we also don't want to memorize five different naming conventions, so we simplify and combine some of the cases.
The first thing we want to distinguish between is variables and constants. On the surface, they seem the same (they both represent some value), but semantically, they're completely different – you can tell just from the name. Variables are meant to always be changing, and constants are meant to never change. Historically, constants were denoted using SCREAMING_CASE (to make them really stand out), so Java programmers generally use this convention as well.
Next, we want to distinguish between classes and variables or methods. The reason for this is because if we don't, we could potentially end up writing code like this:
graphics graphics = (new graphics()).graphics();
This doesn't actually compile, and is a bit of a contrived example, but if does show that if we don't have naming conventions, we could potentially end up using a class, variable, and method, all with the same name. Yikes!
graphics graphics = (new graphics()).graphics(); // ^ ^ ^ ^ // type variable creating object method
However, if we make all classes start with uppercase letters, we can salvage this to:
Graphics graphics = (new Graphics()).graphics();
...which, while not perfect, is at least unambiguous.
Then, the final question remaining is why don't we distinguish between methods, fields, and variables? This is because Java lets us use all three of those things in unambiguous ways anyways, so there's no point in adding our own conventions on top of that:
public class ConfusingButUnambiguous { private int foo; public ConfusingButUnambiguous(int foo) { System.out.println(foo); // local variable System.out.println(this.foo); // field System.out.println(foo()); // method System.out.println(this.foo()); // another way to call the method } public int foo() { return 3; } }