Buğra Güler Buğra Güler - 7 months ago 30
Java Question

Refactoring the adding process

public static void addToUserList(User newUser){

boolean hasFound = false;

for (User user : users) {
if(user.getUserID() == newUser.getUserID()){
System.out.println("DUPLICATED USER ID: " + user.getUserID() + "ALREADY EXISTS");
hasFound = true;
break;
}

}

if(hasFound = false){
users.add(newUser);
}


}


How do I refactor this code? In users arraylist, there shouldn't be duplicate users by ID.

I think using boolean variable is a bit unnecessary but I couldn't find any better solution.

P.Ss: Also if there is a convenion for these kind of coding styles, can you provide a name? Thank you.

Answer

You don't need the boolean, just return from the method if the user exists.

public static void addToUserList(User newUser){
    for (User user : users) {
        if(user.getUserID() == newUser.getUserID()){
            System.out.println("DUPLICATED USER ID: " + user.getUserID() + "ALREADY EXISTS");
            return;
        }
    }

    users.add(newUser);
}