Skip to content
Priyanshu Chauhan edited this page Jun 16, 2014 · 4 revisions

java logo

Java Code Conventions

This note demonstrates the precis version of Java Code Conventions as per the Oracle guidelines.

*Note: This is just a brief overview, for complete Reference visit the oracle website.

What Is a Naming Convention?

A naming convention is a rule to follow as you decide what to name your identifiers (e.g. class, package, variable, method, etc..).

Why Use Naming Conventions?

Different Java programmers can have different styles and approaches to the way they program. By using standard Java naming conventions they make their code easier to read for themselves and for other programmers. Readability of Java code is important because it means less time is spent trying to figure out what the code does, leaving more time to fix or modify it.

To illustrate the point it's worth mentioning that most software companies will have a document that outlines the naming conventions they want their programmers to follow. A new programmer who becomes familiar with those rules will be able to understand code written by a programmer who might have left the company many years before hand.

Picking a Name for Your Identifier

When choosing a name for an identifier make sure it's meaningful. For instance, if your program deals with customer accounts then choose names that make sense to dealing with customers and their accounts (e.g., customerName, accountDetails). Don't worry about the length of the name. A longer name that sums up the identifier perfectly is preferable to a shorter name that might be quick to type but ambiguous.

A Few Words About Cases

Using the right letter case is the key to following a naming convention:

Basic naming convention:

Using the right letter case is the key to following a naming convention:

  • Lowercase : is where all the letters in a word are written without any capitalization (e.g., while, if, mypackage).

  • Uppercase : is where all the letters in a word are written in capitals. When there are more than two words in the name use underscores to separate them (e.g., MAX_HOURS, FIRST_DAY_OF_WEEK).

  • CamelCase : (also known as Upper CamelCase) is where each new word begins with a capital letter (e.g., CamelCase, CustomerAccount, PlayingCard).

  • Mixed case : (also known as Lower CamelCase) is the same as CamelCase except the first letter of the name is in lowercase (e.g., hasChildren, customerFirstName, customerLastName).

Standard Java Naming Convention:

The below list outlines the standard Java naming conventions for each identifier type:

  • Packages : Names should be in lowercase. With small projects that only have a few packages it's okay to just give them simple (but meaningful!) names:
package pokeranalyzer
package mycalculator
  • Classes : Names should be in CamelCase. Try to use nouns because a class is normally representing something in the real world:
class Customer
class Account 
  • Interfaces : Names should be in CamelCase. They tend to have a name that describes an operation that a class can do:
interface Comparable
interface Enumerable
  • Methods : Names should be in mixed case. Use verbs to describe what the method does:
void calculateTax()
string getSurname() 
  • Variables : Names should be in mixed case. The names should represent what the value of the variable represents:
string firstName
int orderNumber 

Only use very short names when the variables are short lived, such as in for loops:

for (int i=0; i<20;i++)
{
    //i only lives in here
} 
  • Constants : Names should be in uppercase.
static final int DEFAULT_WIDTH
static final int MAX_HEIGHT 

Standards we follow for Coding

Tab spaces-

Tab spaces in STS or any editor must be of size 4.
Windows -> Preferences -> Java -> Code Style -> Formatter -> edit any change the Tab size.
Also Tab Policy- Spaces Only

Tab spaces-

Tab spaces in STS or any editor must be of size 4.
Windows -> Preferences -> Java -> Code Style -> Formatter -> edit any change the Tab size.
Also Tab Policy- Spaces Only

Varaible names-

Variable names for domain class must be in the format- Instance. eg. java Domain Class - User then, java def userInstance = new User()

Logic in Controllers & Services-

All logical data & common calculation must be done inside services except for saving or validation.
Service must return the bind unsaved instance to controller. Now Inside controller, first validate the all instances, redirect to edit form if validation fails and then save all instances.

Important Naming Convention that we follow:

There are some common naming convention we follow at different different scenarios:

  1. All source files like .groovy, .java etc must be named as upper camel case. For Example: MyClass.groovy or SimpleJavaProgram.java,
  2. All non source files like images, .css, .js etc, must be all dashed lower case. For Example an image file could be named as my-avatar.png,
  3. All normal directories other then directories in view folder of grails-app, must follow the same naming pattern as above i.e. must be all dashed lower case. For Example: web-app/external-css/jquery-alert.css,
  4. Variables defined in any groovy or java class must be all lower camel case and must be meaningful. For Example:

MyClass.groovy

class MyClass {

    String usersFirstName   // Allowed
    String usersLastName    // Allowed
    String fN               // Not Allowed
    Date bday               // Not Allowed
    Date birthdate          // Allowed
    int t_rating            // Not Allowed
    int totalRating         // Allowed

}
  1. Same goes for method names. They also must be lower camel case. For Example:

SimpleJavaProgram.java

class SimpleJavaProgram {

    private String firstName;

    String getFirstName() {     // Allowed
        return firstName;
    }

    String get_fName() {        // Not Allowed
        return firstName;
    }

    String getFullName(boolean add_title) {     // Not Allowed
        // code here
    } 
}
  1. Constants in Java or groovy classes must be all uppercase separated with dashes. For Example:
class UserData {

    public static final BASE_ID = "UID"
}
  1. These naming patterns are applicable on any type of code we write. For example in java, groovy, javascript, shell script etc.
  2. No grails service names must start with two uppercase letters, since then we are forced to inject them as the class name. This makes code hard to read because now we have some variables with the same name as their class.

References

  1. Standards for Coding
  2. Naming Convention