Skip to content
Advertisement

Optimize the several multiple OR conditions in IF statement

I am new to java and trying to learn a better way of coding.Please let me know if I can replace the multiple OR conditions in the below ELSE IF statement with any other way to execute based on the username passed in the calling method :

public void verifyPermissions(String user, String level2, String Folder) {

        if (user.equalsIgnoreCase("ABC_Username")) {
            verifyXYZPermission(Folder);

            verifyNoPermissionToDelete();

        }

        else if (user.equalsIgnoreCase("DEF_Username") || user.equalsIgnoreCase("GHI_Username")
                || user.equalsIgnoreCase("JKL_Username") || user.equalsIgnoreCase("MNO_Username")
                || user.equalsIgnoreCase("PQR_Username") || user.equalsIgnoreCase("STU_Username")
                || user.equalsIgnoreCase("VWX_Username")) {

            if (user.equalsIgnoreCase("GHI_Username")) {

                verifyNoPermissionToCreate(user, Folder, level2);

                verifyNoPermissionToUpdate(Folder);

            } else {

                verifyCreatePermission(level2);

                verifyPermisssionToUpdate(Folder);
            }
            }
            }

Advertisement

Answer

Here’s one way: define a Set<String> with the possible username values before the if block, and check against it. Notice how all the strings were lower-cased to avoid trouble:

Set<String> userNames = new HashSet<>();
userNames.add("def_username");
userNames.add("ghi_username");
userNames.add("jkl_username");
userNames.add("mno_username");
userNames.add("pqr_username");
userNames.add("stu_username");
userNames.add("vwx_username");

// assuming `user` is non-null
user = user.trim().toLowerCase();

if (user.equals("abc_username")) {
    verifyXYZPermission(Folder);
    verifyNoPermissionToDelete();
} else if (userNames.contains(user)) {
    if (user.equals("ghi_username")) {
        verifyNoPermissionToCreate(user, Folder, level2);
        verifyNoPermissionToUpdate(Folder);
    } else {
        verifyCreatePermission(level2);
        verifyPermisssionToUpdate(Folder);
    }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement