juan_gandhi: (Default)
Juan-Carlos Gandhi ([personal profile] juan_gandhi) wrote2007-05-25 05:26 pm

new trick

I wonder how obvious or how stupid or how ubiquitous is the following trick:

Say, I have an enum somewhere outside of my realm:
enum DataType { 
  PERSONAL,  COMMUNITY, PRISON, ARMY;
};

....





and my method takes an instance of that enum, and I really do not like switching based on the enum; of course I can have an
EnumMap
, but the funny trick is that my strategies are based on this enum type, so I can do just this:
enum Strategy { 
  PERSONAL {
    public void process(Entity entity) {...};
  }, 
  COMMUNITY {
    public void process(Entity entity) {...};
  }, 
  PRISON {
    public void process(Entity entity) {...};
  }, 
  ARMY {
    public void process(Entity entity) {...};
  }

  abstract public void process(Entity entity);
  DEFAULT{
    public void process(Entity entity) {...};
  };

  abstract public void process(Entity entity);

(and so on, add functionality here )

  Strategy forDataType(DataType type) {
    Strategy candidate = valueOf(type.name());
    return candidate == null ? DEFAULT : candidate;
  }
};
....


Strategy.forDataType(myType).process(myEntity);




(PURPLE STUFF ADDED LATER)


Is not it a poetry? :)

[identity profile] ygam.livejournal.com 2007-05-26 12:35 am (UTC)(link)
I didn't know Java has enums.

[identity profile] ivan-gandhi.livejournal.com 2007-05-26 12:47 am (UTC)(link)
Wow. Not only it has them, but they are a very efficient tool. Check out Josh Bloch's article (http://java.sun.com/features/2003/05/bloch_qa.html). There was a better one, but I could not find it... and it may be an internal publication anyway.

[identity profile] ygam.livejournal.com 2007-05-26 01:01 am (UTC)(link)
I only used Java 1.5 once in the last 4 1/2 years, and generics was the only new feature I took advantage of.