new trick

May. 25th, 2007 05:26 pm
juan_gandhi: (Default)
[personal profile] juan_gandhi
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? :)

Date: 2007-05-26 10:24 am (UTC)
nine_k: A stream of colors expanding from brain (Default)
From: [personal profile] nine_k
I enjoy seeing mainstream static languages moving to more and more dynamic grounds.

Recently I enjoyed learning about java.lang.reflect.Proxy that allows one to construct classes on the fly.

Date: 2007-05-26 02:19 pm (UTC)
From: [identity profile] ivan-gandhi.livejournal.com
You probably know about Guice (pronounced as juice)?

Date: 2007-05-26 05:53 pm (UTC)
nine_k: A stream of colors expanding from brain (Default)
From: [personal profile] nine_k
Very very little. (Frankly, I did not do any serious Java development since about 2002, and only track things superficially.)

I can imagine a fully static class construction path, either via bytecode assembler or by full-blown java source generation and complilation, and then loading the class file. I could imagine Guice to work this way :)

But to quote project homepage, "Guice cures tight coupling," "Guice is the anti-static." This all sounds pretty to my dynamic-languages-inclined ear :)

Profile

juan_gandhi: (Default)
Juan-Carlos Gandhi

May 2025

S M T W T F S
    1 2 3
456 7 8 9 10
11 121314151617
181920 21 222324
25262728293031

Most Popular Tags

Page Summary

Style Credit

Expand Cut Tags

No cut tags
Page generated May. 25th, 2025 08:03 am
Powered by Dreamwidth Studios