Many Java developers, including myself, like using the typesafe constant idiom because it provides cleaner code by removing the need to validate whether a constant value is valid or in range. I don’t detail too much here, as the idiom is well documented both in JavaWorld and in several books (see Resources below).
This idiom’s canonical form, shown below, uses the ==
operator to compare values:
public final class NumberConstants{ public static final NumberConstants ONE=new NumberConstants(); public static final NumberConstants TWO=new NumberConstants(); public static final NumberConstants THREE=new NumberConstants(); private NumberConstants(){} } void test(NumberConstant num){ //No need to check that the value is on range if(num==NumberConstant.ONE){ //take some action } }
Using the idiom this way works well until you need to make the class serializable. Vladimir Roubtsov discusses the problem with serialization and offers an elegant solution in “Java Tip 122: Beware of Java Typesafe Enumerations.”
Find A Teacher Form:
https://docs.google.com/forms/d/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ/viewform?edit_requested=true#responses
Email:
public1989two@gmail.com
www.itsec.hk
www.itsec.vip
www.itseceu.uk