Tuesday, August 16, 2005

Using the type-safe enumeration pattern in Java

I just completed some programming duties, pairing with another developer at my day job. We needed to add some new attributes to an address, specifically an address type and a foreign address indication. Instead of making these String types, we used Josh Bloch's type-safe enum pattern and narrowed the interface contract to AddressType and ForeignAddressIndicator types. Worked out great. I've seen a lot of Java source lately that just passes ints and Strings and does nothing to validate that the values are correct for the usage. This pattern works well for this validity checking, limiting the possible values and allowing the compiler to enforce type safety.

1 comment: