Site icon Experiences Unlimited

Java Programming Style Guide


The Java language gives you all the room you need to write code that would be very difficult for others to understand. Java also permits you to write code that is very easy to understand. Most development teams would prefer the latter.

A style guide provides provides a map so that the code generated by a group of programmers will be consistent and, therefore, easier to read and maintain. Many people do not care for the style guide offered by Sun. This document is one alternative.

This document covers most areas where there could be confusion or difference of opinion. Areas that have never been a problem in our experience are undocumented.

1 – Formatting

1.1 – Indentation

1.2 – Spacing

1.3 – Class Member Ordering

class Order
// fields

// constructors

// methods

1.4 – Maximum Line Length

Avoid making lines longer than 120 characters.

1.5 – Parentheses

Parentheses should be used in expressions not only to specify order of precedence, but also to help simplify the expression. When in doubt, parenthesize.

2 – Identifiers

All identifiers use letters (‘A’ through ‘Z’ and ‘a’ through ‘z’) and numbers (‘0’ through ‘9’) only. No underscores, dollar signs or non-ascii characters.

2.1 – Classes and Interfaces

All class and interface identifiers will use mixed case. The first letter of each word in the name will be uppercase, including the first letter of the name. All other letters will be in lowercase, except in the case of an acronym, which will be all upper case.

2.2 – Packages

Package names will use lower case characters only. Try to keep the length under eight (8) characters. Multi-word package names should be avoided.

2.3 – All Other Identifiers

3 – Coding

3.1 – Constructs to Avoid

3.2 – Do Not Compound Increment Or Decrement Operators

3.3 – Initialization

Declare variables as close as possible to where they are used.

3.4 – Access

All fields must be private, except for some constants.

4 – Self-Documenting Code

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”

— Martin Fowler, Refactoring: Improving the Design of Existing Code

Rather than trying to document how you perform a complex algorithm, try to make the algorithm easier to read by introducing more identifiers. This helps in the future in case the algorithm changes but someone forgets to change the documentation.

Source: JavaRanch

Exit mobile version