CHAPTER 2 ■ JAVA SYNTAX
often used as a suggested limit for the length of a line. If you get to 80 characters, find a way to divide the
line into two lines. (The 80-character value comes from punch cards having 80 characters.) You can
certainly have longer lines (and there are times when it's acceptable), but hold down on really long lines,
for sanity's sake.
Avoid Overly Complex Code
There's an old joke in which one person writes, “Simplify!” and someone else rewrites it as “Eschew
Obfuscation.” Coding is a lot like writing in some ways (in fact, we enjoy both because of the
similarities). One such way is that you often have choices about how to do things. Although it might be a
fun challenge to see how complex you can make a line, you should avoid coding that way. Your fellow
developers will thank you, and you'll thank yourself when you come back to an old project, if your code
is as readable as possible. Let's consider an example in Listing 2-4:
Listing 2-4. Dense code
someValue = someMethodToGetABooleanValue() != someOtherMethodToGetABooleanValue()?
someMethodToDoSomething() : someMethodToDoSomethingElse();
The issue here is density. The previous line has too much meaning in one place. So let's rewrite it
into simpler code in Listing 2-5.
Listing 2-5. Simplified code example
boolean firstBooleanValue = someMethodToGetABooleanValue();
boolean secondBooleanValue = someOtherMethodToGetABooleanValue();
if (firstBooleanValue != secondBooleanValue) {
someMethodToDoSomething();
} else {
someMethodToDoSomethingElse();
}
Don't worry about the details. Just consider the structure. We get to the meaning of all these bits and
pieces later in this chapter and the next chapter.
Notice that the simplified code is much longer. Rather than one line of code (on two lines of the file),
the simplified code occupies eight lines of code. Simplification definitely has a cost (making you scroll
more to read it). However, it's far more readable. You (and your fellow developers) can understand it
quickly, where you (probably) have to stop and puzzle out the meaning of the single, dense line.
Some developers would say that we over-simplified the code. They'd point out that the two boolean
variables don't really help (the methods that return those values could be in the if) and that the braces
are unnecessary (you don't need braces for if and else if the block belonging to each is only one line
long). Those things are true. The code would look something like Listing 2-6.
Listing 2-6. Moderately simplified code
if (someMethodToGetABooleanValue() != someOtherMethodToGetABooleanValue())
someMethodToDoSomething();
else
someMethodToDoSomethingElse();