I\'m trying to make a simple switch case console menu for a few different users: admin
, moderator
, and user
. admin
would
you are better off with a map of functions or Actions.
var actionsAdmin = new Dictionary<string, Action>{
{"create", ()=>Console.WriteLine("create")}
{"modify", ()=>Console.WriteLine("modify")}
}
var actionsUser = new Dictionary<string, Action>{
{"show", ()=>Console.WriteLine("show")}
{"foodle", ()=>Console.WriteLine("foodle")}
}
then choose the right map and execute the named function
var action = actionUser[verb];
action();
Switch (no pun intended) it around do check for role at each case. And then if it is not allowed to do it, skip it.
string i = Console.ReadLine();
if (allowed(userType, i)){
switch(i):
case "create": Console.WriteLine("Created");
handleCreate();
break;
case "show":Console.WriteLine("Showed");
handleShow();
break;
case "delete":Console.WriteLine("Deleted");
handleDelete();
break;
default: Console.WriteLine("Default");
handleDefault(userType);
break;
}
This is a good candidate for the strategy pattern.
In the strategy pattern, functionality is represented by an object of an interface that can be passed around. Different implementations allow the behaviour to change dynamically.
For example:
interface ConsoleInteractor
{
void performAction(string action);
}
class UserConsoleInteractor : ConsoleInteractor
{
public void performAction(string action)
{
switch(i)
{
case "create":
Console.WriteLine("Created");
break;
case "show":
Console.WriteLine("Showed");
break;
default:
Console.WriteLine("Default");
break;
}
}
}
The dynamic equivalent of a switch-case is a dictionary lookup. For example:
Dictionary<string, Action> userActions = {
{ "create", () => Console.WriteLine("created") },
{ "show", () => Console.WriteLine("showed") } };
Dictionary<string, Action> adminActions = {
{ "create", () => Console.WriteLine("created") },
{ "show", () => Console.WriteLine("showed") },
{ "delete", () => Console.WriteLine("deleted") } };
Dictionary<string, Dictionary<string, Action>> roleCapabilities = {
{ "user", userActions },
{ "administrator", adminActions } };
roleCapabilities[userType][action]();
At runtime, you can easily add and remove allowed actions to each role (group).
In order to implement "default" logic, you'd use something like:
Action actionCall;
if (roleCapabilities[userType].TryGetValue(action, out actionCall)) {
actionCall();
}
else {
// this is the "default" block, the specified action isn't valid for that role
}