Saturday, 6 April 2013

Java Code Conventions


Sun estimated that over the lifetime of a standard piece of code, 20 percent of the effort will go into the original creation and testing of the code, and 80 percent of the effort will go into the subsequent maintenance and enhancement of the code. Agreeing on, and coding to, a set of code standards helps to reduce the effort involved in testing, maintaining, and enhancing any piece of code. Sun had created a set of coding standards for Java, and published those standards in a document cleverly titled "Java Code Conventions," which you can find at
http://www.oracle.com/technetwork/java/codeconv-138413.html. It's a great document, short and easy to read and we recommend it highly.  Here are the naming standardsthat Sun recommends, and that we use in the exam and in most of the book:

Classes and interfaces

The first letter should be capitalized, and if several words are linked together to form the name, the first letter of the inner words should be uppercase (a format that's sometimes called "camelCase"). For classes, the names should typically be nouns. For example:
Dog
Account
PrintWriter

For interfaces, the names should typically be adjectives like

Runnable
Serializable
Methods

The first letter should be lowercase, and then normal camelCase rules should be used. In addition, the names should typically be verb-noun pairs. For example:
getBalance
doCalculation
setCustomerName
Variables

Like methods, the camelCase format should be used, starting with a lowercase letter. Sun recommends short, meaningful names, which sounds good to us. Some examples:
buttonWidth
accountBalance
myString
Constants

Java constants are created by marking variables static and final. They should be named using uppercase letters with underscore characters as separators:
MIN_HEIGHT