Tuesday, November 8, 2011

Usage EnumSet instead of boolean variables

I had a Java class which contained a lot of boolean variable definitions as I show below
boolean specialFlag1;
boolean specialFlag2;
boolean specialFlag3;
boolean specialFlag4;
specialFlag1 = true;
if (specialFlag1){
It looked very bad and made my code ugly so I decided to extract the variables into an enum
public enum SpecialFlag {
so the boolean variables part of the core class was changed to the code below
final Set specialFlags = EnumSet.noneOf(SpecialFlag.class);
if (specialFlags.contains(SpecialFlag.Flag1){
as you can see above, the EnumSet based variant looks really better but I was worrying about productivity and wrote a small test to compare the speed of working with the EnumSet variant and the boolean one. My test shows that difference between boolean and EnumSet variants is no so big and about 13%.

No comments:

Post a Comment