The third article in the series of “Effective Java – Key Points” is here.

  1. Use Strategy Pattern when the algorithm/strategy is to be chosen at the run-time. E.g. Choosing the algorithm based on file format, file compression, etc. In this case, declare an Interface for the strategy and then implement the interface for a different algorithm.
  2. Never use raw types.

    List l = new ArrayList();

    Using raw types might end up in run-time exceptions because of adding incompatible objects to the list. Always use generics so that the compiler can identify the incompatible data types.

    List<String> l = new ArrayList<String>
  3. Never ignore the unchecked warning from the compiler. Fix these warning as much as possible to keep the code safe in terms of casting and conversion. At least provide a “Suppress warning” annotation in a minimum scope.
  4. Type Erasure: The generics concept introduced in Java 1.5 is only for the compatibility check at the compile time, thereby reducing the compatibility and casting issues at the run-time. Thus the concept of “type erasure” come into picture wherein the compiler erases the type information and make the references raw. Hence, the compiler will make the bytecode run in JVM as if there were no generics thereby reducing the changes on JVM.
  5. Always ensure to validate the parameters passed to constructor or method. This is a good practice because otherwise the program might fail with a wrong exception or silently compute wrong results.
  6. Prefer defensive copying while designing public API. The client using the code might mutate/change the value of the object.  In case the class is package scoped and the developer knows the usage then it is good to avoid defensive copying because it is costly in terms of memory.
  7. Prefer two element enum types instead of boolean parameters to improve the readability of the code.     E.g.
    public enum TemperatureScale { FAHRENHEIT , CELSIUS }
  8. Prefer BigDecimal for monetary calculation as float and double work on binary floating point arithmetic and cannot represent 0.1 accurately.
  9. Use checked exceptions in case of recoverable conditions where the application can recover from the exception and continue the execution without any flaws. Use unchecked exception to indicate programming errors. In case of programming errors, it is better to terminate the application instead of silently doing wrong stuff.
  10. The types of nested classes are


One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s