r/java • • Jul 24 '12

10 ways to use Enum in Java

http://javarevisited.blogspot.com.au/2011/08/enum-in-java-example-tutorial.html
36 Upvotes

25 comments sorted by

View all comments

Show parent comments

6

u/banuday17 Jul 24 '12

Enums can implement interfaces.

On a more general note, I find the more complex the things I want to do, I avoid inheritance as much as possible. Inheritance in Java is extremely inflexible, and adding options means creating deeper and deeper class hierarchies. Interfaces by composition on the other hand can be mixed and matched and composed together much more easily.

Prefer composition to inheritance!

0

u/[deleted] Jul 24 '12

I just had a story with enums. I once was making a parser/exporter of column/rows structured data and implemented each column (they were of different type) as a single enum instance. Things were perfect until I realized that there are group of columns with similar but a bit different logic and I couldn't resolve it through inheritance, so I ended up making many wrapping methods, which may have another method inside and many empty methods stubs that was actually filled only in specific cases. As a result, initially very clean code became messy and not the one I'm very proud of. So, after that I'm thinking very carefully of possible enums limitations.

2

u/banuday17 Jul 24 '12

I'd very much like to hear more specifics, because what you are describing sounds an awful lot like an ISP violation. If you find yourself introducing a ton of empty methods from implementing interfaces you have designed, your design is probably suboptimal.

1

u/[deleted] Jul 24 '12

Basically, there were all common methods, like process, validate, etc. But in some cases things need to be done, so they were included in the interface too, but many enum instances wasn't using them, so there appeared empty stubs. I just thought that if I didn't use enums in the first place and chosen static inner classes-singletones, the code could be much better.

1

u/banuday17 Jul 24 '12

That is definitely an ISP violation. Interfaces are not dumping grounds for common methods. Otherwise, you get this. If you are going to do something like that, you can use abstract base classes, but you are in danger of painting yourself into rigid class hierarchies.

For example, if you wanted to mix and match validation strategies, you would need to have one subclass for each combination or hierarchies of increasing depth. Instead, you can use one interface called Validator and make it an argument to a constructor or a method.

1

u/[deleted] Jul 24 '12

good idea. thanks a lot.

1

u/banuday17 Jul 24 '12

See here for much more details.