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 12:35 am (UTC)
From: [identity profile] ygam.livejournal.com
I didn't know Java has enums.

Date: 2007-05-26 12:47 am (UTC)
From: [identity profile] ivan-gandhi.livejournal.com
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.

Date: 2007-05-26 01:01 am (UTC)
From: [identity profile] ygam.livejournal.com
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.

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

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

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.

(no subject)

From: [identity profile] ivan-gandhi.livejournal.com - Date: 2007-05-26 02:12 pm (UTC) - Expand

(no subject)

From: [identity profile] spamsink.livejournal.com - Date: 2007-05-26 02:56 pm (UTC) - Expand

(no subject)

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

(no subject)

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

(no subject)

From: [identity profile] spamsink.livejournal.com - Date: 2007-05-26 03:10 pm (UTC) - Expand

(no subject)

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

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

Date: 2007-05-26 04:53 am (UTC)
From: [identity profile] ivan-gandhi.livejournal.com
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?

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

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

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

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

(no subject)

From: [identity profile] ivan-gandhi.livejournal.com - Date: 2007-05-26 06:38 pm (UTC) - Expand

(no subject)

From: [identity profile] http://users.livejournal.com/d_m_/ - Date: 2007-05-26 08:04 pm (UTC) - Expand

(no subject)

From: [identity profile] ivan-gandhi.livejournal.com - Date: 2007-05-26 10:03 pm (UTC) - Expand

(no subject)

From: [identity profile] http://users.livejournal.com/d_m_/ - Date: 2007-05-26 10:06 pm (UTC) - Expand

Date: 2007-05-26 05:31 pm (UTC)
From: [identity profile] pvax.livejournal.com
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)

From: [identity profile] http://users.livejournal.com/d_m_/ - Date: 2007-05-26 05:48 pm (UTC) - Expand

(no subject)

From: [identity profile] pvax.livejournal.com - Date: 2007-05-26 06:12 pm (UTC) - Expand

(no subject)

From: [identity profile] http://users.livejournal.com/d_m_/ - Date: 2007-05-26 08:09 pm (UTC) - Expand

(no subject)

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

(no subject)

From: [identity profile] http://users.livejournal.com/d_m_/ - Date: 2007-05-27 10:53 am (UTC) - Expand

(no subject)

From: [identity profile] pvax.livejournal.com - Date: 2007-05-28 04:13 pm (UTC) - Expand

(no subject)

From: [identity profile] ivan-gandhi.livejournal.com - Date: 2007-05-26 06:39 pm (UTC) - Expand

(no subject)

From: [identity profile] selfmade.livejournal.com - Date: 2007-05-26 11:33 pm (UTC) - Expand

(no subject)

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

(no subject)

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

(no subject)

From: [identity profile] pvax.livejournal.com - Date: 2007-05-28 04:09 pm (UTC) - Expand

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

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

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

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

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

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

(no subject)

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

(no subject)

From: [identity profile] http://users.livejournal.com/d_m_/ - Date: 2007-05-26 05:52 pm (UTC) - Expand

(no subject)

From: [identity profile] ivan-gandhi.livejournal.com - Date: 2007-05-26 10:07 pm (UTC) - Expand

(no subject)

From: [identity profile] http://users.livejournal.com/d_m_/ - Date: 2007-05-26 10:38 pm (UTC) - Expand

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 :)

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

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

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

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


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

(no subject)

From: [identity profile] furia-krucha.livejournal.com - Date: 2007-05-26 02:39 pm (UTC) - Expand

(no subject)

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

(no subject)

From: [identity profile] furia-krucha.livejournal.com - Date: 2007-05-26 05:53 pm (UTC) - Expand

(no subject)

From: [identity profile] ivan-gandhi.livejournal.com - Date: 2007-05-26 06:40 pm (UTC) - Expand

(no subject)

From: [identity profile] http://users.livejournal.com/d_m_/ - Date: 2007-05-26 08:25 pm (UTC) - Expand

(no subject)

From: [identity profile] ivan-gandhi.livejournal.com - Date: 2007-05-26 10:01 pm (UTC) - Expand

(no subject)

From: [identity profile] http://users.livejournal.com/d_m_/ - Date: 2007-05-26 10:24 pm (UTC) - Expand

(no subject)

From: [identity profile] furia-krucha.livejournal.com - Date: 2007-05-26 09:16 pm (UTC) - Expand

(no subject)

From: [identity profile] ivan-gandhi.livejournal.com - Date: 2007-05-26 09:49 pm (UTC) - Expand

(no subject)

From: [identity profile] furia-krucha.livejournal.com - Date: 2007-05-27 08:07 pm (UTC) - Expand

(no subject)

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

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

Style Credit

Expand Cut Tags

No cut tags
Page generated May. 24th, 2025 07:49 pm
Powered by Dreamwidth Studios