Posts tagged with : best-practices

Choosing the right collection

Here is a quick guide for selecting the proper implementation of a Set, List, or Map in your application.

The best general purpose or ‘primary’ implementations are likely ArrayList, LinkedHashMap, and LinkedHashSet. Their overall performance is better, and you should use them unless you need a special feature provided by another implementation. That special feature is usually ordering or sorting.

Here, “ordering” refers to the order of items returned by an Iterator, and “sorting” refers to sorting items according to Comparable or Comparator.


Using Eclipse effectively

To ensure that the code that you write is always clean and complaint to your project specific coding standards and guidelines, it is important that you configure your eclipse to effectively use its compiler settings, Formatter, CheckStyle and related built in features. Most developers wouldn’t bother to do so but trust me that it is huge time saver in long run and shall always keep your code quality under check.

Following spread sheet has the configuration that we use in our current projects. You can customize these settings according to your development standards and needs.

Also ideally your Eclipse should be configured with your “code formatter” and “CheckStyle” XML configurations.


Best practices for threadsafe Singletons

A singleton class should be designed to ensures that there exists only one instance per application. Special care must be taken if your application is deployed on a clustered environment as in this case it is possible that multiple instance of your singleton class are available in your application.

Here are a few ways to create a thread safe singleton classes in your application.


Overloading can be tricky

Extra care must be taken while writing Overloading methods. The compiler decides which version of an overloaded method will be called based on declared compile-time type, not run-time type. For the case in which overloaded methods have the same number of arguments, the rules regarding this decision can sometimes be a bit tricky.

If there may be confusion, you may simplify the design:

  • use different method names, and avoid overloading altogether
  • retain overloading, but ensure each method has a distinct number of arguments
  • In addition, it is recommended that varargs not be used when a method is overloaded, since this makes it more difficult to determine which overload is being called.


Prefer using parameterized types over raw types

When generics were introduced in JDK 1.5, raw types were retained only to maintain backwards compatibility with older versions of Java. Although using raw types is still possible, they should be avoided for following reasons :

  • they usually require casts
  • they aren’t type safe, and some important kinds of errors will only appear at runtime
  • they are less expressive, and don’t self-document in the same way as parameterized types


Prefer switch over if-else

In most cases switch will be lighter and performs faster than an if/else ladder. The compiler is able to optimize switch statements into a lookup table and perform compile-time checking for literals when dealing with enumerations, so I’d suggest that it’s usually preferable to use switch over if/else if if you’re dealing with numeric or enum types in Java.

Exception handling guidelines/best practices

Let’s review some basic exception design guidelines, summarized from Object Design: Roles, Responsibilities, and Collaborations (Rebecca Wirfs-Brock and Alan McKean, Addison-Wesley, 2003).

  • Don’t try to handle coding errors: Unless your software is required to take extraordinary measures in error scenarios, don’t spend a lot of time designing it to detect and recover from programming errors. In the case of an out-of-bounds array index, divide-by zero error, or any other programming error, the best strategy is to fail fast (and leave an audit trail of the problem that can be used to troubleshoot it).
  • Avoid declaring lots of exception classes: Create a new exception class only when you expect some handling of the code to take a significantly different action, based on the exception type. In my experience it is rarely the case and exception classes available in java API serve the purpose.


Avoiding null pointer exceptions

Null pointer exceptions(NPE) are the undoubtedly the most common and most annoying errors. In most cases I have observed that it could have been avoided by simply sticking to some best coding practices while writing code. Here is an example of a potential NPE.

private Boolean isExpired(final StatusEnum status) {
    if (status.equals(StatusEnum.EXPIRED)) { // Potential null pointer if status is null.
        return Boolean.TRUE;
    } else {
        return Boolean.FALSE;


Crave for immutable classes

In the book “Effective Java”, Joshua Bloch makes this compelling recommendation :

“Classes should be immutable unless there’s a very good reason to make them mutable….If a class cannot be made immutable, limit its mutability as much as possible.”

Immutable objects are objects whose data or properties cannot be changed after it is constructed. JDK has a number of immutable class like String and Integer. Immutable objects have big list of compelling positive qualities and they can greatly simplify your program. Immutable objects :


Ajax primer

The term Ajax has come to represent a broad group of web technologies that can be used to implement a web application that communicates with a server in the background, without interfering with the current state of the page. In the article that coined the term Ajax, Jesse James Garrett explained that the following technologies are incorporated:

  1. HTML (or XHTML) and CSS for presentation
  2. The Document Object Model (DOM) for dynamic display of and interaction with data
  3. XML for the interchange of data, and XSLT for its manipulation
  4. The XMLHttpRequest object for asynchronous communication
  5. JavaScript to bring these technologies together


Use PMD - Programming Mistake Detector?

About PMD

How do you ensure that your code follows standard programming principles? For most Java development projects going on these days the answer would be to use “PMD”. It is aiming towards becoming a de-facto tool for analyzing the source code and is being used by more and more Java applications everyday.

Note: There are a lot many tools that PMD competes with i.e Checkstyle, FindBugs, Hammurapi, Soot, Squale etc. However exploring capabilities of these tools(other than PMD) are out of scope of this article.

PMD is a static rule set based Java source code analyzer that identifies potential problems in the code like:


Beware of floating point numbers

Outside of a scientific or engineering context, the use of float and double (and the corresponding wrapper classes Float and Double ) should likely be avoided. The fundamental problem is that rounding errors will always occur when using these data types - they are unavoidable.

In a typical business application, using float and double to represent money values is dangerous, because of these rounding issues. Instead, BigDecimal should usually be used to represent money. It is also a common practice to have utility classes like “” that are wrappers over “BigDecimal” class of the JDK and that provides helper methods and functionality as needed by the business application.


Use final liberally. Please do.

Use the final keyword liberally to communicate your intent. The final keyword has more than one meaning :

  • a final class cannot be extended
  • a final method cannot be overridden
  • final fields, parameters, and local variables cannot change their value once set

In the last case, “value” for primitives is understood in the usual sense, while “value” for objects means the object’s identity, not its state. Once the identity of a final object reference is set, it can still change its state, but not its identity. Declaring primitive fields as final automatically ensures thread-safety for that field.


Overridable methods need special care

Allowing a method to be overridden should always be done intentionally, not by accident.

Any method which is not private, static, or final can be overridden. Over-ridable methods, and any methods which call them, represent unusual places in your code, to which special attention must be paid. This is because sub-classing violates encapsulation, in the sense that it is possible for a subclass to break its superclass’s contract. If you do not intend a method to be overridden, then you should declare it as private, static, or final.


Prefer composition over inheritance

Trust me on this one, I have learnt it the hard way. To start with lets start with the understanding of the terms composition and inheritance.

  • Composition
    • Functionality of an object is made up of an aggregate of different classes
    • In practice, this means holding a pointer to another class to which work is deferred
    • Collaboration is implemented simply by forwarding all calls to an object field
    • It has no dependence on implementation details of the object field
    • It is more flexible, since it is defined dynamically at run-time, not statically at compile-time
  • Inheritance
    • Functionality of an object is made up of it’s own functionality plus functionality from its parent classes


Visit the archives!