user1884155
user1884155

Reputation: 3736

Is it bad practice to have the order of an enum declaration matter?

Let's say I have the enum AccessRole with 3 declarations:

public Enum AccessRole
{
    Admin,
    User,
    ReadOnly;
}

I use the ordinal value of this enum to denote the concept of "hierarchical" access role. For example,

if (currentRole.ordinal() < otherRole.ordinal())
{
    //We know currentRole has more user rights than otherRole, because it's ordinal is smaller.
}

I don't base any rights of the ordinal, but I use the ordinal to sort and compare the enum values when necessary (for example, in the user interface, to sort all possible access roles by ordinal from "many rights" to "limited rights").

This works fine, but I'm concerned that this is not clear. If any other developer were to insert a new accessrole at the bottom of the enum instead of at the correct ordinal, the whole system is messed up.

Is there any way to deal with this? That this, impose an order on enum declarations, yet make it clear in the code semantically that the order is important/being used?

Upvotes: 2

Views: 3327

Answers (3)

Stephen C
Stephen C

Reputation: 719376

While the order of enums is not normally considered as being important, the way I would address this case (where it does matter) would be to put a prominent comment in the source code.

Sure, you can't protect against programmers who modify (butcher!) your code without reading the comments. But on the other hand:

  • they are liable to butcher your code in other ways anyway, and

  • ultimately, if they ignore your comments and break the code as a result, they should take the blame.

Upvotes: 2

Jens Schauder
Jens Schauder

Reputation: 82008

You are rightly concerned. The order of enums is often not considered important by developers.

Yet adding another artifical ordinal just make things worse, because now you have take care that the numbers are different, and the meaning of the new ordering is still not clear.

I think what would help is to move the check for privileges in the Enum. So have method in your Enum that looks like this:

public boolean includes(Role otherRole){
    return (this.ordinal() < otherRole.ordinal())
}

Now you can add tests. And every developer worth her money will understand that changing the order of things in the enum is actually a change in business logic.

Upvotes: 3

Vikdor
Vikdor

Reputation: 24134

How about adding an integer attribute to the Enum and document that it is used for maintaining the hierarchy of roles. This also allows to define two roles at the same level.

Upvotes: 1

Related Questions