In C I've done this sort of thing
enum { USE_COKE = 1,
USE_PEPSI = 2,
USE_JUICE = 4,
USE_WATER = 8 };
int makeDrink(int flags);
//...
int rcode = makeDrink(USE_COKE | USE_JUICE | USE_WATER);
I know this is pretty standard, it's also used in iostream
for instance. I'm wondering how to translate this design pattern into Java or OOP? I'm pretty sure polymorphism is not the way to go here since it'd be better for my code to have an if(flag_is_set)
block than rewrite much of the routine. Is there a utility Flags
class, or a preferred way to do this using a configuration object, or an enum
, or a bunch of ints, etc.
You have also Java EnumMap, so you can get the value from the
EnumMap
of all theUSE_XXX
needed for your drink before pass the sums of them to your methodJava has enumerations. Here's the tutorial.
I would use these over ints etc. It's a type-safe solution, and since enums are objects, you can attach behaviours and avoid
switch
statements.You can combine these (as above) using an EnumSet. From the doc:
There are multiple options to implement this.
The Answer by Brian Agnew is correct. Java has a powerful, flexible, and downright handy
Enum
facility. (Not to be confused with the now-outmodedEnumeration
interface.)Example Code
Here is example code based on the question.
A method taking an
EnumSet
of that enum type.Code calling that method, instantiating and passing the necessary
EnumSet
.When run.
Keep in mind these are real objects, type-safe, compiler-enforced, statically defined, and self-documenting. Do not mistake them for mere strings.