Buğra Güler
Buğra Güler

Reputation: 25

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.

Upvotes: 2

Views: 69

Answers (2)

Nir Levy
Nir Levy

Reputation: 12953

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);
}

Upvotes: 3

suulisin
suulisin

Reputation: 1434

please try with this.Change the == in first if to != like below and remove the last part

public static void addToUserList(User newUser){

    boolean hasFound = false;

    for (User user : users) {
        if(user.getUserID() != newUser.getUserID()){

            users.add(newUser);
        } 

    else{
          System.out.println("DUPLICATED USER ID: " + user.getUserID() + "ALREADY EXISTS");
       }

    }


}

Upvotes: 0

Related Questions