For my trading program, I have a Merchant class. A given Merchant object may or may not have a particular special quality or bundle of special qualities. For example, one Merchant object may have the Stockbroker quality, another Merchant may have the Financial Services and Stockbroker qualities, and another Merchant may have no special qualities at all.
My initial thought was to create a HashMap and a Qualities class as follows:
Map<Qualities, Boolean> merchantQualities = new HashMap<Qualities, Boolean>();
The only problem is, there are at least 50 possible special qualities for Merchants, such that it would be extremely tiresome to subclass all the qualities from the Quality class.
Is there a better way of coding for these optional special qualities and representing them in the Merchants class than a HashMap and subclassing a Qualities class?
This all depends on what
Qualities
are and what they do. If the list is fairly stable,enum
s can be a good solution:The good thing about
enum
s is they basically are classes so the can implement interfaces and have state and behaviour. They also come with useful helper classes:and then you can use all the
Set
functions likecontains()
etc.But I can't tell you if this is an appropriate solution for you without knowing more information.
Edit: a common starting point for this in many languages is enums. In C/C++/C# this would go something like:
Here's how Java's enums are better. Let's say you define another enum for stock type:
If you make the assumption a given merchant type sells one type of thing:
so instead of saying:
you say:
Java enums have state and behaviour. That's an extremely powerful concept.
But you can do better than this. Instead of assuming one stock per merchant, this is better handled by behaviour:
at which point your code becomes:
which is a far more natural, readable and extensible solution.