Rewrite method to decide the ShowLevel based on roles I have different roles in my system.


HOD
Staff
Non staff


I am having a form at the front end and fields shall be visible to only users with specific roles.

The ShowInGui levels are like this:


Show to All
Show to staff/HOD
Show to HOD


Any other do not show

I am planning to write a method which will take the user role and decides the access.

Could this method be better written?

public boolean canBeShownInGUI(Role role, int showInGui) {
    if (showInGui == 1) {
        return true;
    } else if (showInGui == 2 &amp;&amp; (role == Role.HOD || role == Role.STAFF)) {
        return true;
    } else if (showInGui == 3 &amp;&amp; role == Role.HOD) {
        return true;
    } else 
      return false;
   }
I presume Role is an enum (if it is not, it should be). An enum is a great candidate for a switch statement, and it also makes the conditions very clear:

switch (role) {
    case HOD:
        return showInGui &gt;= 1;
    case STAFF:
        return showInGui == 1 || showInGui == 2;
}
return showInGui == 1;


Note that, if you want you can embed that logic in to the enum itself, and have a simple call to an enum method:

return role.isVisible(showInGui);


Additionally, if you reverse the values of the showInGui to be:

0 -&gt; nobody
1 -&gt; HOD only
2 -&gt; HOD &amp; STAFF
3 -&gt; everyone


then your logic is simplified further to:

switch (role) {
    case HOD:
        return showInGui &gt;= 1;
    case STAFF:
        return showInGui &gt;= 2;
}
return showInGui &gt;= 3;