the source

Tuesday, December 1, 2009

Java Coding – Best Practises – 1

This is the first in a series of posts covering best practices for java coding.

As with most things in life, there are few hard-and-fast rules. Best practices for Java coding are no exception. Treat the following as guidelines, and remember to add comments to your code wherever you choose to ignore them.

Don’t use strings in loops

String numbers = "";
for(int i = 0;i < 10; i++) {
    numbers = numbers + "," + i;

This code is inefficient because in each loop it creates an immutable string and then in the next loop discards the string and replaces it with a new one. This leads to poor performance.

Instead, use the StringBuilder (Java 1.6+) or StringBuffer (Java 1.4+). They are both mutable strings.

StringBuilder sb = new StringBuilder();
for(int i = 0; i < 10; i++) {
String numbers = sb.toString();

Testing strings for equality

To avoid null pointer exceptions when testing for equality between a string variable and a constant string, always use the constant string first.

public void doLoginStuff(final String action) {
    if("login".equals(action) {
        // do something
    } else {
        // do something else

Unless you want the code to throw a null pointer exception, in which case you should generally provide a comment explaining why.

Don’t use magic numbers or strings

Consider the following code:

if(obj.getWorkflowState() == 53) {
   // do something

1. The meaning of 53 is completely unknown without further investigation.
2. A developer could change this value to some other integer and completely break the code (even though it would compile).

Use an enum instead:

public enum WorkflowState {

    private int workflowStateNumber;

    WorkflowState(final int stateNumber) {
        workflowStateNumber = stateNumber;

    public String toString() {
        return "Workflow State: " + workflowStateNumber;

// now when you want to use it (as before):

if(WorkflowState.DATA_SAVED.equals(obj.getWorkflowState()) {
   // do something

1. It is much more obvious what the if statement means.
2. There is now a compile-time check that reduces the risk of a mistake.

Note also that the constant is specified first in the if statement. This avoids any possible null pointer exception that would otherwise have been thrown if obj.getWorkflowState() had returned null.

posted by Jason at 10:54 am  

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment


Powered by WordPress