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 05:42 am (UTC)
From: [identity profile] spamsink.livejournal.com
Suppose someone added a new element into the original enum and has not touched your code. The compile will succeed without any warning in your case, but with a switch there will be one.

Date: 2007-05-26 02:12 pm (UTC)
From: [identity profile] ivan-gandhi.livejournal.com
With the switch, there will be a default case in most cases. With enum, watch it, I'll add a check.

Date: 2007-05-26 02:56 pm (UTC)
From: [identity profile] spamsink.livejournal.com
Я правильно понял, что проверка будет производиться лишь однажды?

Date: 2007-05-28 05:06 am (UTC)
From: [identity profile] spamsink.livejournal.com
Теперь понятно. Да, более "функционально", чем свич, но все равно, на мой взгляд, на уровне синтаксического сахара.

Проверка на идентичность enum-ов, а она существенна, при очередном редактировании потерялась.

Date: 2007-05-26 03:10 pm (UTC)
From: [identity profile] spamsink.livejournal.com
If you have a separate and different action to take for each enum value, you don't need a default. While we're at it, how would you implement a default action here?

Date: 2007-05-28 05:02 am (UTC)
From: [identity profile] ivan-gandhi.livejournal.com
I don't know. It depends. In the case of my app, it is just reporting success (I know it's stupid; I'll fix it later, I just started).

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
25 262728 293031

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated May. 29th, 2025 09:20 pm
Powered by Dreamwidth Studios