M
M
malomalo2019-03-01 23:43:11
Java
malomalo, 2019-03-01 23:43:11

What is the correct way to check the uniqueness of an object in Java before creating it?

Please advise how to correctly organize the check for the uniqueness of an object before creating it.

public class User {
    private String name;
    private static Set<String> onlineUsers = new HashSet<>();

    public User(String name) { this.name = name; onlineUsers.add(name); }
    public void logoutUser() { onlineUsers.remove(this.name); }
    public String getName() { return name; }
}

I have a User class, I want to exclude the creation of users with the same name, for this I want to write all the names in the HashSet and before creating a new User object I will check if such a name exists. How to properly organize the validation logic (is it correct to include it in this class):
1. in the constructor before creating a new User object? Is it okay for a constructor to throw an Exception?
2. in the place in the code where I call the constructor of the new User object, but in this case it remains possible to create two identical objects (in another place in the code where a similar check will not be implemented).
3. make the constructor private and add a public static addNewUser method that will check if there is a user with the same name, call the constructor and return a reference to the new object? What should this method return if the specified object already exists, and should it throw an Exception?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Iloveski, 2019-03-02
@Iloveski

For my taste, option 3. To throw an exception or not and how to handle it depends on the logic of the place where you create the user'a. Only method is better to call createUser or createNewUser

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question