Panasonic Youth rob sanheim writes about software, business, ruby, music, stuff and things



Posted
4 January 2006 @ 6pm

Tagged
Agile, Java

Discuss

Keeping enums/constants DRY?

I'm pretty sure there is no way to do this with Commons Enum (yes, I'm stuck on 1.4) using plain ole java. Say you just want every enum to have the same attribute name as its variable name, like so:

JAVA:
  1. private static int index = 0;
  2.         private final static SalesOrgType DISTRICT = create("DISTRICT");
  3.     private final static SalesOrgType SALES_STATE = create("SALES_STATE");
  4.     private final static SalesOrgType CORPORATE = create("CORPORATE");
  5.     private final static SalesOrgType REGION = create("REGION");
  6.  
  7.     private static SalesOrgType create(String name) {
  8.         return new SalesOrgType(name, index++);
  9.     }

...without specifying the name of the enum twice in each declaration? I.e. if I create an enum var as FOO, I want it to be created with "FOO" passed in to the constructor for the name?

You also see this pattern often in String constants:

JAVA:
  1. public final static String USER_KEY = "USER_KEY";

Annoying. I'm guessing the only pure java solution would be to declare your variables, then reflectively look for everything of type x in the class and get their names. Then call setName with the field name of each thing. This would break your immutability and would be hackish and complex to boot.


2 Comments

Posted by
Tom Hawtin
5 January 2006 @ 1pm

You could use code generation…

The chance of error can be reduced by lining the string literal up directly below the identifier.

Or just move onto 1.5. It’s been out for well over a year now.


Posted by
Rob
5 January 2006 @ 1pm

I realize code gen would work, I just dont think the additional complexity would pay off for something that is pretty simple. Unless you have some insane amount of constants/enums around.

Re: 1.5 - I’ve moved for personal projects long ago. Its client work that I can’t control. =)


Leave a Comment

THIS IS NO GAME 100 cups of coffee in 48 hours