| The Elements of Good Java Style       by Rob Signorelli |
Despite what many think, software development is more than simply "making
it work." True, a program that doesn't work is useless, but consider the
following scenario: I ask you to add some more functionality to a piece of code.
I tell you that I'll give you some code to start. Would you rather I hand you this
piece of code:/**
* This method adds all of the numbers in the numbers parameter and adds
* them to the existing total given in the second parameter. For instance,
* if your collection "nums" has the numbers 3,4,5 in it and you call the
* method as such addAllElementsToTotal(nums, 7), the results will be 19.
*/
public int addAllElementsToTotal(Collection numbers, int startingTotal)
{
int sum = startingTotal;
// Iterate all of the numbers, adding them for the existing total
Iterator numberIterator = numbers.iterator();
while( numberIterator.hasNext() )
{
Integer number = (Integer)numberIterator.next();
sum += number.intValue();
}
return sum;
}or this one: public int methodwhereiaddstuff(Collection c,int i) {
int x=i;Iterator it=c.iterator();
while(it.hasNext()){ Integer asdf=(Integer)it.next();
x+=asdf.intValue();} return x;}Most of you, I'm sure, would like me to give you the first piece of code to start with (if you feel that the second snippet is more elegant, I fear for your success in this course). Both pieces of Java code accomplish the same task and produce the same result (trust me), but it's amazing what a different that things like spacing, indenting. and good variable/method names can have to someone having to read the code. The rest of this document outlines some of the basics of "good style" that will ultimately results in more readable code which will make your grader's life easier as well as yours should you ever have to go back and alter existing code. I only scratch the surface with this guide. After reading this, you will only have good enough style not to get dirty stares from other programmers. There is much more to good style than this... but this is a nice start :)
Disclaimer Although many of these conventions are the steadfast rules, no ifs ands or buts about it... many of these are simply guidelines that may not be appropriate 100% of the time. Let experience and feedback from others also dictate when to use and when to not use some of these conventions. Ultimately the point of these conventions is to make your code "pretty" and easy to read. There ARE cases where following these rules will hinder that, so use your best judgement and strive to make your code aesthetically pleasing. |
| Spacing |
If you learn nothing in the way of Java style, remember this: whitespace is your
friend! When you compile Java code, whitespace is ignored. By ignored, I don't mean that
your code will compile if you have no spaces. I mean the following code snippets are
exactly the same to the compiler;int x = (8 + y) * 2; int x=(8+y)*2; int x = (8 + y) * 2; The Java compiler doesn't care how you write this statement, however the first example is by far the easiest to read. The second is too cluttered and it's hard to discern where the values are and where the operators are. The third is spread way too far apart to make sense.
Rule Place a single space between operators (=, +, *, etc) and operands. Also, use parenthesis as desired to enhance the readability of really long one-line expressions. Spacing is important beyond simply clarifying operators and operands. Methods also have some general spacing rules of thumb. To avoid a lengthy explanation, here are examples of good and bad ways to declare and call methods in your code: Good Declaring: public void myMethod(int arg1, int arg2, String arg3) Calling: myMethod(5, 6, "hello there"); Bad Declaring: public void myMethod(int arg1,int arg2,String arg3) Calling: myMethod(5,6,"hello there"); The code I provided above has some keywords colored which helps to make sense of the argument list in myMethod(), but depending on your editor of choice, figuring out the arguments may take some extra effort in the latter case because the code is so packed together. Similarly, when calling this method, placing a space after each comma helps to visually make sense of what each argument is.
Rule When declaring or calling a method/function, place a space after every comma. |
| Indenting |
PAY ATTENTION! Indenting is one of the most important facets of Java coding style.
What purpose does this serve? It tells whoever is reading the code "how" the code
runs and where certain blocks of code reside. This is important when dealing with
if's, loops, and methods so we can easily figure out what lines of code are associated
with the given structure. Take note of the indenting pattern in the following examples:
/**
* I can easily read what lines are the
* body of the if clause because they
* are indented
*/
x = 4 * y;
boolean isValid = true;
if( isValid )
{
x = 0;
System.out.println("Setting x to 0");
}/**
* The indenting shows me what code makes
* up the body of the while loop. Furthermore
* I indent even more for the body of the
* if statement for clarity
*/
x = 4 * y;
boolean isValid = true;
while( isValid )
{
x += 5;
System.out.println("Setting x to 0");
if( x > 100 )
{
isValid = false;
}
}/**
* This last example shows a basic example
* as to how to indent your entire file. Notice
* the "cue" we see that tells us it's time to
* indent...
*/
import java.util.*;
public class MyClass
{
public String m_message;
public void countToTen(boolean skipFour)
{
int i;
for( i = 1; i != 10; i++ )
{
if( i == 4 && skipFour )
{
System.out.println("---");
}
else
{
System.out.println("Number: " + i);
}
System.out.println("... looking for next number");
}
System.out.println("I counted to 10, YAY!");
}
public void getMessage()
{
return m_message;
}
}
I won't bother showing the case where all of the lines of code are lined up on the left, but trust me that staring at such code is not for the faint of heart! One thing to notice is that each indentation occurs the LINE AFTER AN OPEN CURLY BRACE! Another subtle note, each of these indentations are 4 spaces or 1 tab (where 1 tab = 4 spaces).
Rule Indent 4 more spaces on the line after any opening curly brace "{". Stop that level of indenting when you reach the corresponding closing curly brace "}". |
| Naming Conventions |
|
I'm probably sounding like a broken record, but knowing
how to name your variables and methods is one of the most
important keys to writing readable, easy to understand
code. There are 3 main rules, each of which are very simple,
but equally as easy to stray from.
Rule Use DESCRIPTIVE variable and method names in your code. The names should imply their use. If you have a variable that represents a running total, name it something like "total" or "sum"... not "x". This may mean that you will sometimes end up with extremely long variable names such as "initialStartingTotal", but resist the urge to just use the variable "x" or "y" or something very non-descriptive. Otherwise, should you need to reference this code again, you'll probably spend more time relearning how the code worked than you did typing the extra characters in the first place. The second rule of naming deals specifically with the nature of naming methods/functions. Suppose you have a method whose purpose is to set the value "age" in a class (don't worry if you don't know what that means yet... you will). Alternately, suppose you have a method that returns the value of the same "age" property. The proper naming conventions for those methods are as follows (assuming that the "age" property is of type int): public void setAge(int age) public int getAge() Notice that the method that updates the property starts with "set" and the method that returns the value starts with "get". Collectively these types of methods are known as "getters and setters", but all of these should follow this naming convention.
Rule Methods whose main purpose is to update the value of an existing variable within a class should begin with "set". Those whose purpose is to return some value should begin with "get". Other extraneous methods are only bound by the other naming conventions mentioned here. The last naming convention deals with method and variable names that have more than one word in them. Not all of your variables/methods can be easily represented by something like "total." Frequently, you will need more than one word to accurately describe a variable's/method's purpose. For instance, maybe you need to store the base lengths for a number of geometric shapes (squares, trapezoids, etc). Well, the variable "base" is quite ambiguous... what shape is that base for? So we need something like "trapezoid base length" or "square base length". The problem is that we can't have spaces in our variable (or method) names. Hence, we adopt the following convention:
Rule All variable and method names start with a lower case letter! Use capital letters to visually separate multiple words used in the same name. For variables, this might mean something like "trapezoidBaseLength". For methods, this would be more like "calculateSalesTaxAccurately()". Alternately, there are similar styles for naming classes and files (those that end in .java). In a nutshell, the naming convention is the same for classes and file names except that the first letter in these is ALWAYS a capital letter. This provides a clear distinction between variable names and class names without anyt effort. The rest of the rules as far as multiple words apply.
Rule All class names and .java files should begin with a CAPITAL LETTER. The remainder of the name should be in lower case except when the start of a new word occurs. So the class name would resemble "ComputerUser" and the corresponding .java file would be "ComputerUser.java". |
| Comments |
|
Comments, despite whatever human you think holds this
title, are your best friend. When you look at a new piece
of code that is hundreds/thousands of lines long, you will
want some plain English sprinkled here and there to explain to
you what's going on so you don't have to analyze the code
for hours to understand it. Remember... the compiler just
ignores comments. They are only there for us humans (or
any other life form capable of analyzing computer code). We have 2 types of comments at our fingertips: block comments, and line comments. Block comments begin with /* and end with */. Line comments start with // and end whenever the end of the line is reached. This guide won't go into the specifics about how to use them. There are plenty of resources available about that. But the general rule to follow is add a block comment before every function giving a short description of its use. And use line comments in your code when you feel that a specific chunk of code could use some english explanation. You do not have to comment "everything". Much of the code you write will be intuitively obvious to any programmer what you are doing and requires no added commentary. But when your code starts to get long and hairy, throw them in to make reading the code a much more pleasant experience. The following example is not necessarily the ideal commenting template. In fact, no such thing exists. Instead, just use this to pick up on the sorts of things that you should be commenting and the things (like declaring your variables) may not need it (note, the algorithm in this example is not exactly the best implementation, but for the sake of showing usage of comments, it will serve our purposes): /*
* This method reads in a file and
* stores the results in a collection,
* outputs every line, then returns the
* collection.
*/
public Collection getAndPrintLinesFromFile(String fileName)
{
Collection lines = new ArrayList();
try
{
String currentLine;
FileReader fileReader = new FileReader(fileName);
BufferedReader reader = new BufferedReader(fileReader);
// Read each line of the file and store it in the Collection
while( (currentLine = reader.readLine()) != null )
{
lines.add(currentLine);
}
// Iterate all of the collection entries and print
// them to the console
Iterator lineIterator = lines.iterator();
while( lineIterator.hasNext() )
{
System.out.println((String)lines.next());
}
}
catch( Exception e )
{
// Ignore any errors
}
return lines;
}
And there you have it. There is much more to knowing Java style than I've shown you, but this is definitely a heck of a start, and there are cases where you can throw some of these ideas out the window. Basically there's far more than I can possibly hope to relay in a web page. Let experience be your guide. Look at the code that others write (for style purposes... not for getting the answer to your homework) and eventually you will become a great, stylish coder. Be off and fair well, grasshopper. |