Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I better represent user permissions?

In my system I have a single class with a load of (20?) final booleans defining the permissions this user type has.

What is a better way to do this?

I'm sure there's lots of examples about this but I don't know the keywords.

like image 502
Nick Avatar asked Aug 03 '10 12:08

Nick


1 Answers

You can take advantage of enums, e.g.:

public enum Permission {
    READ, WRITE;
}

public class User {

    private final EnumSet<Permission> permissions;

    public User(Permission... permissions) {
       this.permissions = EnumSet.copyOf(Arrays.asList(permissions));
    }

    public boolean hasPermission(Permission permission) {
        return permissions.contains(permission);
    }

    //...
}

User user = new User(Permission.READ, Permission.WRITE);
like image 139
Vitalii Fedorenko Avatar answered Sep 28 '22 12:09

Vitalii Fedorenko