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.

[identity profile] spamsink.livejournal.com 2007-05-26 01:11 am (UTC)(link)
What's the main difference between a switch and copying the list of enum constituents into another enum?

[identity profile] ivan-gandhi.livejournal.com 2007-05-26 04:52 am (UTC)(link)
You "copy" once; then you dispatch; switch is forever, and you are bound to have a long list of statements, just because.

[identity profile] spamsink.livejournal.com 2007-05-26 05:42 am (UTC)(link)
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.

(no subject)

[identity profile] ivan-gandhi.livejournal.com - 2007-05-26 14:12 (UTC) - Expand

(no subject)

[identity profile] spamsink.livejournal.com - 2007-05-26 14:56 (UTC) - Expand

(no subject)

[identity profile] ivan-gandhi.livejournal.com - 2007-05-28 04:58 (UTC) - Expand

(no subject)

[identity profile] spamsink.livejournal.com - 2007-05-28 05:06 (UTC) - Expand

(no subject)

[identity profile] spamsink.livejournal.com - 2007-05-26 15:10 (UTC) - Expand

(no subject)

[identity profile] ivan-gandhi.livejournal.com - 2007-05-28 05:02 (UTC) - Expand

[identity profile] selfmade.livejournal.com 2007-05-26 02:46 am (UTC)(link)
В C# такое было всегда, правда с явным приведением типа:
return (Strategy) Enum.Parse(typeof(Strategy), type.ToString());

[identity profile] ivan-gandhi.livejournal.com 2007-05-26 04:53 am (UTC)(link)
Wait, looks weird. And c# people do it, when they have to map an enum to an enum? How come Java people did not do it?

[identity profile] selfmade.livejournal.com 2007-05-26 02:37 pm (UTC)(link)
Убрать явное приведение из синтаксиса и будет то же самое, что и в твоём примере. Так что и Java люди делают это. Или пример из Java как раз о том, что приведение типов автоматически делается?

[identity profile] pvax.livejournal.com 2007-05-26 07:09 am (UTC)(link)
Err... And you've got to use reflection in Java instead of cast? Well, you can call it "poetry", very slow though.

[identity profile] ivan-gandhi.livejournal.com 2007-05-26 02:17 pm (UTC)(link)
How would you use cast here? (And, again, what's wrong with this kind of reflection?)

[identity profile] http://users.livejournal.com/d_m_/ 2007-05-26 03:15 pm (UTC)(link)
Там не совсем reflection, но поиск элемента по имени, причём путём полного перебора элементов enum #1. В настоящем mapping всё-таки есть хеширование. Но если автору так не нравится Map, почему бы не делать так, как положено, т.е. в каждый элемент enum #2 поместить элемент из enum #1, задавая эту связь в конструкторе? И работает шустрее некуда, и assert не просит :)

(no subject)

[identity profile] ivan-gandhi.livejournal.com - 2007-05-26 18:38 (UTC) - Expand

(no subject)

[identity profile] ivan-gandhi.livejournal.com - 2007-05-26 22:03 (UTC) - Expand

[identity profile] pvax.livejournal.com 2007-05-26 05:31 pm (UTC)(link)
Not in Java, of course. In C#:

enum DataType { PERSONAL, COMMUNITY, PRISON, ARMY };

enum Strategy { PERSONAL, COMMUNITY, PRISON, ARMY };

Strategy ForDataType(DataType type)
{
return (Strategy)type;
}
I know it's a dirty hack but it works.

(no subject)

[identity profile] pvax.livejournal.com - 2007-05-26 18:12 (UTC) - Expand

(no subject)

[identity profile] pvax.livejournal.com - 2007-05-27 06:58 (UTC) - Expand

(no subject)

[identity profile] pvax.livejournal.com - 2007-05-28 16:13 (UTC) - Expand

(no subject)

[identity profile] ivan-gandhi.livejournal.com - 2007-05-26 18:39 (UTC) - Expand

(no subject)

[identity profile] selfmade.livejournal.com - 2007-05-26 23:33 (UTC) - Expand

(no subject)

[identity profile] pvax.livejournal.com - 2007-05-27 07:06 (UTC) - Expand

(no subject)

[identity profile] ivan-gandhi.livejournal.com - 2007-05-28 05:07 (UTC) - Expand

(no subject)

[identity profile] pvax.livejournal.com - 2007-05-28 16:09 (UTC) - Expand

[identity profile] caseq.livejournal.com 2007-05-26 09:17 am (UTC)(link)
Надо рассказывать как это красиво делается на темплейтах в C++, или ты в курсе? :)

[identity profile] ivan-gandhi.livejournal.com 2007-05-26 02:14 pm (UTC)(link)
Да, пожалуйста. Я уже давно не сишник.

[identity profile] http://users.livejournal.com/d_m_/ 2007-05-26 09:56 am (UTC)(link)
А можно буквально в двух словах, чему именно нужно восхищаться в этом коде?

[identity profile] ivan-gandhi.livejournal.com 2007-05-26 02:18 pm (UTC)(link)
Краткостью. Есть другие решения?

[identity profile] http://users.livejournal.com/d_m_/ 2007-05-26 02:30 pm (UTC)(link)
А какая задача решалась? :))

[identity profile] http://users.livejournal.com/d_m_/ 2007-05-26 03:04 pm (UTC)(link)
Кстати, а фиолетовый код вчера был?

(no subject)

[identity profile] ivan-gandhi.livejournal.com - 2007-05-26 17:31 (UTC) - Expand

(no subject)

[identity profile] ivan-gandhi.livejournal.com - 2007-05-26 22:07 (UTC) - Expand
nine_k: A stream of colors expanding from brain (Default)

[personal profile] nine_k 2007-05-26 10:24 am (UTC)(link)
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.

[identity profile] ivan-gandhi.livejournal.com 2007-05-26 02:19 pm (UTC)(link)
You probably know about Guice (pronounced as juice)?
nine_k: A stream of colors expanding from brain (Default)

[personal profile] nine_k 2007-05-26 05:53 pm (UTC)(link)
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 :)

[identity profile] mikkim08.livejournal.com 2007-05-26 10:44 am (UTC)(link)
Так вот иногда думаешь, что Джава не такой уж и плохой язык. Просто библиотеки у него плохие

[identity profile] furia-krucha.livejournal.com 2007-05-26 11:09 am (UTC)(link)
Is not it a poetry? :)
На дадаизм похоже, да. :-)

Проблема в том, что если кто-то outside of your realm добавит новое значение в enum DataType, то статическими методами этого обнаружить нельзя, и результатом будет исключение в процессе исполнения.

"Uncaught java.lang.InvalidCast exception in class mil.NORAD.ControlLoop, commencing emergency launch."


[identity profile] ivan-gandhi.livejournal.com 2007-05-26 02:26 pm (UTC)(link)
Так уж и нельзя обнаружить.

(no subject)

[identity profile] ivan-gandhi.livejournal.com - 2007-05-26 17:33 (UTC) - Expand

(no subject)

[identity profile] ivan-gandhi.livejournal.com - 2007-05-26 18:40 (UTC) - Expand

(no subject)

[identity profile] ivan-gandhi.livejournal.com - 2007-05-26 22:01 (UTC) - Expand

(no subject)

[identity profile] ivan-gandhi.livejournal.com - 2007-05-26 21:49 (UTC) - Expand

(no subject)

[identity profile] ivan-gandhi.livejournal.com - 2007-05-28 05:10 (UTC) - Expand