Wednesday, October 8, 2008

Javolution

This can best be described with the following sentence: If you use Java use Javolution!

Go to their API and read it... pick anything you can use and then use it!

Saturday, October 4, 2008

To Enum or not to Enum? ENUM!!!

Using public static final as enum has many problems, such as:

  • Not typesafe - Since a type is just an int you can pass in any other int value where a particular type is required, or add two types together (which makes no sense). This is particularly noticeable in C programs where you will find strange constants being used in un-related place and yet it seems to work, simply because the required constant and the provided constant share the same int value.
  • No namespace - You must prefix constants of an int enum with a string to avoid collisions with other int enum types.
  • Brittleness - Because such enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined.
  • Printed values may be uninformative - With int as enum (as in public static final int), if you print one out all you get is a number, which tells you nothing about what it represents, or even what type it is. In Java enums you get full type information along with value.

public enum FruitCategory { SWEET, CITRUS }

public enum Fruit {
APPLE
{ FruitCategory getCategory() {return FruitCategory.SWEET;} },
BANANA
{ FruitCategory getCategory() {return FruitCategory.SWEET;} },
ORANGE
{ FruitCategory getCategory() {return FruitCategory.CITRUS;} },

abstract FruitCategory getCategory();
}