tag:blogger.com,1999:blog-4084458860381242516.post3356850179376445063..comments2023-11-26T20:18:14.351-08:00Comments on Putting the tea into team: Java Enums with constant-specific methodsIvan Moorehttp://www.blogger.com/profile/09119134602348298270noreply@blogger.comBlogger2125tag:blogger.com,1999:blog-4084458860381242516.post-80127695038245747412009-11-30T04:49:51.299-08:002009-11-30T04:49:51.299-08:00I'm big fan of this approach too - (you don...I'm big fan of this approach too - (you don't need java 1.5 enums, it works the with old type-safe-enum class pattern).<br /><br />There's a rule of thumb I find useful for deciding when polymorphism is better than the alternative case statement.<br /><br />With strategy-enums like this you have 2 considerations, the number of instances and the number of methods. Or more pertinently how these might grow.<br /><br />Consider the alternative :<br />public enum Operation {<br /> PLUS, MINUS, TIMES, DIVIDE;<br /><br /> double eval(double x, double y) {<br /> switch (this) {<br /> case PLUS :<br /> return x + y;<br /> case MINUS :<br /> return x - y;<br /> case TIMES :<br /> return x * y;<br /> case DIVIDE :<br /> return x / y;<br /> }<br /> throw new Defect();<br /> }<br />}<br /><br />With the polymorphic approach adding a new Operation instance is easy while adding a new method is trickier<br />The opposite is similarly true.<br /><br />My own caveat - when in doubt, go for polymorphism.Str8yhttps://www.blogger.com/profile/06381145747513579691noreply@blogger.comtag:blogger.com,1999:blog-4084458860381242516.post-53124106067276486432009-11-25T00:17:10.230-08:002009-11-25T00:17:10.230-08:00Although this is very useful (I'm a big fan of...Although this is very useful (I'm a big fan of that polymorphism stuff myself), you have to remember that you are effectively creating an anonymous extension of the actual enum class.<br /><br />ie. Printing out the class name of PLUS would result in:<br /><br />Operation$1<br /><br />This can cause issues such as if you attempt to serialise/deserialise it. We encountered this issue over a Hessian connection if I remember correctly.<br /><br />This problem can be overcome by un-abstracting the object method and passing a Closure-like function into the constructor which is called in the now concrete method. Slightly uglier, but it works... :)dirtyhttps://www.blogger.com/profile/06202830424034782851noreply@blogger.com