I have an User class like this:
public class User
{
public double userId;
public Role userRole;
....
}
Role is an enum like this:
enum Role
{
ADMIN,
REGISTERED,
UNREGISTERED
}
I have a class called UserActions, which is like this:
public class UserActions
{
private User user;
public UserActions(User user){ this.user = user; }
public void Create(){...}
public void Read(){...}
public void Update(){...}
public void Delete(){...}
}
Now, obviously, whether an user is able to use Create, Read, Update or Delete depends on their role. The naive way to do this is to use Guard clauses in all the methods based on user.role, but that is definitely not elegant, and it pollutes the business logic.
What I want to do is something like this:
public class UserActions
{
private User user;
public UserActions(User user){ this.user = user; }
public ArrayList<Lambdas> allowedActions() { return a list of allowed actions for the user which they can then invoke}
private void Create(){...}
private void Read(){...}
private void Update(){...}
private void Delete(){...}
}
Is there a way to return an array of methods the user can call based on their roles in Java?
Look at following approach. I think you're almost there for the solution, just use Function
instead of inline methods. I think it should work.
class UserActions {
private final Function<Context, Result> create = context -> Result.NULL;
private final Function<Context, Result> read = context -> Result.NULL;
private final Function<Context, Result> update = context -> Result.NULL;
private final Function<Context, Result> delete = context -> Result.NULL;
private User user;
public UserActions(User user) {
this.user = user;
}
public List<Function<Context, Result>> allowedActions() {
// TODO read credentials and provided allowed actions here
return List.of(create, read, update, delete);
}
public static final class Context {
// TODO add action's input data here
}
public static final class Result {
public static final Result NULL = new Result();
// TODO read action's result here
}
}
I think that client should identify different methods, then instead of List
you can provide a Map
with unique key for each action, e.g. CREATE
, READ
, UPDATE
and DELETE
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments