Reputation: 2662
In my chat application I have an enum:
enum ContactRelationType {
Friend,
Familiar,
Ignored,
Unknown,
Guild,
Officers,
Academy,
Community,
System
}
Half of ContactRelationType values are rooms (Guild, Officers, Academy, Community, System). I need to know is the value room or not.
I know three ways to do it:
The first:
enum ContactRelationType {
Friend,
Familiar,
Ignored,
Unknown,
Guild,
Officers,
Academy,
Community,
System;
public boolean isRoom() {
return this == Guild ||
this == Officers ||
this == Academy ||
this == Community ||
this == System;
}
}
It looks ugly and the IDEA tells me "Overly complex boolean expression" and it is.
The second:
enum ContactRelationType {
Friend,
Familiar,
Ignored,
Unknown,
Guild,
Officers,
Academy,
Community,
System;
public boolean isRoom() {
switch (this) {
case Guild:
case Officers:
case Academy:
case Community:
case System:
return true;
default:
return false;
}
}
it looks ugly too.
The third:
public enum ContactRelationType {
Friend(false),
Familiar(false),
Ignored(false),
Unknown(false),
Guild(true),
Officers(true),
Academy(true),
Community(true),
System(true);
private boolean room;
ContactRelationType(boolean room) {
this.room = room;
}
public boolean isRoom() {
return room;
}
}
But in this case I have boolean room
in all enum instances.
So, what solution is better and why?
Upvotes: 2
Views: 75
Reputation: 115328
You solution with boolean flag is good. Just add a default constructor:
ContactRelationType() {
this(false);
}
Now you do not have to write true
or false
for each enum member; only for those that are not "default":
public enum ContactRelationType {
Friend,
Familiar,
Ignored,
Unknown,
Guild(true),
Officers(true),
Academy(true),
Community(true),
System(true);
Upvotes: 5
Reputation: 65811
You probably could use an EnumSet
. They are very efficiently implemented with a BitSet
equivalent.
enum ContactRelationType {
Friend,
Familiar,
Ignored,
Unknown,
Guild,
Officers,
Academy,
Community,
System;
public boolean isRoomRelation() {
return RoomContacts.contains(this);
}
}
static final Set<ContactRelationType> RoomContacts = EnumSet.of(
ContactRelationType.Guild,
ContactRelationType.Officers,
ContactRelationType.Academy,
ContactRelationType.Community,
ContactRelationType.System);
Upvotes: 4