About Tomasz Nurkiewicz

Java EE developer, Scala enthusiast. Enjoying data analysis and visualization. Strongly believes in the power of testing and automation.

Java Coding Conventions considered harmful

There is an official Code Conventions for the Java Programming Language guide published on Oracle site. You would expect this 20+ pages document to be the most complete, comprehensive and authoritative source of good practices, hints and tips with regards to the Java language. But once you start to read it, disappointment followed by frustration and anger increases. I would like to point out the most obvious mistakes, bad practices, poor and outdated advices given in this guide. In case you are a Java beginner, just forget about this tutorial and look for better and more up-to-date reference materials. Let the horror begin!2.2 Common File Names:

GNUmakefile The preferred name for makefiles. We use gnumake to build our software.  
gnumake to build Java projects? ant is considered old-school, so is maven. Who uses maketo build WARs, JARs, generate JavaDocs…?3.1.1 Beginning Comments: All source files should begin with a c-style comment that lists the class name, version information, date, and copyright notice: Putting a class name in the comment starting a file? What if I change my mind and rename the class later? And what should that ‘ date‘ represent? Some people use various placeholders to insert last modification time of a file automatically by version control system. Well, VCS is there to tell you when the file was created or last modified – and modifying the same line over and over again makes merging a huge pain.4 – Indentation: Four spaces should be used as the unit of indentation. The exact construction of the indentation (spaces vs. tabs) is unspecified. Tabs must be set exactly every 8 spaces (not 4).Probably the most counterintuitive part of the document. Some prefer spaces, others (including me) – tabs. A matter of taste and team arrangements. But this guide suggests to use both and replace spaces with tabs, sometimes. It’s ‘ unspecified‘. My advice: use tabs and let each developer configure his IDE to have as big or as small indentations as desired.

4.1 Line Length:

Avoid lines longer than 80 characters, since they’re not handled well by many terminals and tools.

80 characters? My laptop can easily fit three times as much. Strive for 120-140 characters in one line, but don’t use hard-wraps. Personally I just display vertical margin and the

right line length is dictated by readability. BTW here are few examples of classes from various libraries and frameworks:

And we are suppose to fit whole line in 80 characters?

5.1.2 Single-Line Comments:

if (condition) {

    /* Handle the condition. */
    ...
}

Just in case the code is not self-descriptive enough, I suggest even better comment:

if (condition) {

    /* This block is executed if condition == true. */
    ...
}

5.1.3 Trailing Comments:

if (a == 2) {
    return TRUE;            /* special case */
} else {
    return isPrime(a);      /* works only for odd a */
}

Did you mean (and don’t tell me it’s less readable, even without comments)?

return a == 2 || isPrime(a);

6.1 Number Per Line:

int level; // indentation level
int size;  // size of table

Why use descriptive variable names, when we have comments! Consider this instead:

int indentationLevel;
int tableSize;

Later in that section: In absolutely no case should variables and functions be declared on the same line. Example:

long dbaddr, getDbaddr(); // WRONG!

Sure it’s wrong, it doesn’t even compile. I’m surprised that ‘ don’t put spaces in variable names ‘ is not mentioned as a good practice…

6.3 Placement:

Put declarations only at the beginning of blocks. [...] Don’t wait to declare variables until their first use; it can confuse the unwary programmer [...] This is how the coding conventions want you to write your code:

int min;            //inclusive
int max;            //exclusive
int distance;
List<String> list;  //one per each item

min = findMin();
max = findMax();
distance = max - min;
list = new ArrayList<>(distance);
//...

And this is how it should be written to avoid confusion:

final int minInclusive = findMin();
final int maxExclusive = findMax();
final int distance = maxExclusive - minInclusive;
final List<String> listOfItems = new ArrayList<>(distance);
//...

Besides we can finally ( nomen est omen) use final keyword. Later in this section code sample is shown with class fields missing private modifier (default, package private access). Package private field?

7.3 return Statements:

return (size ? size : defaultSize);

Maybe you haven’t noticed, but from the context we can tell that both size and defaultSize are of boolean type. That’s right, size and defaultSize can be either true or false (!) How counterintuitive is that! From such a document I would expect not only syntactical correctness, but also meaningful code and good practices! Moreover, the expression can be greatly simplified, step-by-step:

size ? size : defaultSize
size ? true : defaultSize
size || defaultSize

7.5 for Statements:

An empty for statement (one in which all the work is done in the initialization, condition, and update clauses) should have the following form:

for (initialization; condition; update);



empty for statement‘? Why would you ever use an empty for statement? This is confusing and should be avoided, not encouraged and described in the official language guide.

Bonus quiz: what’s the purpose of this code in C?

while(*dst++ = *src++);

I believe every computer programmer should understand the code snippet above. Even if you program in Ruby or TSQL.

7.8 switch Statements:

Every time a case falls through (doesn’t include a break statement), add a comment where thebreak statement would normally be.


I understand the intentions, but the approach is wrong. Instead of documenting unexpected and error-prone code-fragments, just avoid them. Don’t depend on fall through, don’t use it at all.

8.1 Blank Lines:

One blank line should always be used in the following circumstances:

[...]

  • Between the local variables in a method and its first statement
  • Before a block [...] or single-line [...] comment
  • Between logical sections inside a method to improve readability


Looks like the authors suggest using blank lines to separate  ’logical sections of a method‘. Well, I call these sections: ‘ methods‘. Don’t group statements inside methods in blocks, comment them and separate from each other. Instead extract them into separate, well named methods!

Placing a blank line between variable declarations and the first statement sounds like taken from a C language book.

8.2 Blank Spaces:

  • All binary operators except . should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment (‘++‘), and decrement (‘--‘) from their operands. Example:

[...]

while (d++ = s++) {
  n++;
}

This doesn’t even compile in Java…

9 – Naming Conventions (only in PDF version):

char *cp;

A good name for a char pointer in Java is cp. Wait, WHATchar pointer in Java?

10.1 Providing Access to Instance and Class Variables:


Don’t make any instance or class variable public without good reason. 
Really, really good reason! Did I ever used public field?

10.4 Variable Assignments:

if (c++ = d++) {        // AVOID! (Java disallows)
    ...
}

Great advice: please avoid using constructs that do not even compile in Java. This makes our lives so much easier!

10.5.2 Returning Values:

if (booleanExpression) {
    return true;
} else {
    return false;
}

should instead be written as

return booleanExpression;

Holy cow, I AGREE!

Summary

It’s not that the official Code Conventions for the Java Programming Language are completely wrong. They are just outdated and obsolete. In the second decade of the XXI century we have better hardware, deeper  understanding of code quality and more modern sources of wisdomCode Conventions… were last published in 1999, they are heavily inspired by C language, unaware of billions of lines of code yet to be written by millions of developers. Code conventions should emerge over time, just like design patterns, rather than be given explicitly. So please, don’t quote or follow advices from official guide ever again.

Reference: Java Coding Conventions considered harmful from our JCG partner Tomasz Nurkiewicz at the Java and neighbourhood blog.

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

4 Responses to "Java Coding Conventions considered harmful"

  1. Siva Prasad Reddy says:

    I think instead of maintaining this legacy material, Oracle should just point the users to go and read Uncle Bob’s “Clean Code”.

  2. I’d like to point out, that the line length issue is still questionable. The fact that your laptop can display a lot more, doesn’t mean that everybody else’s devices can. Besides, one might need to see other things on their screens as well, not just have the code taking up all the wide-screen area.

    I for one have found, that while debugging, or doing three way merges, 120+ lines can be quite inconvenient.
    Posting wide code snippets on the web also doesn’t work well sometimes.

    So, while 80 characters is indeed really short, you should consider carefully on what project you are working on and who will be reading it. For example, I don’t think having longer lines is a good idea for widely-used open-source libraries.

  3. Wide line coder says:

    Nowadays, all tools support more than 80 characters per line and all monitors support more than 640 pixels width.

    That line length recommendation is severely outdated.

Leave a Reply


seven + = 9



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books