A
A
Amir Kenesbay2021-02-02 18:59:43
Java
Amir Kenesbay, 2021-02-02 18:59:43

How to do user validation?

I have a validateUser method and it should throw an AccessDeniedException which I created myself. And I wrote like this:

public static void validateUser(User user) throws AccessDeniedException{
        if(user.getAge()<18){
            throw new AccessDeniedException("Access Denied");
        }else{
            System.out.println("Age access granted");
        }
    }


And the question is how to display it in the main method, well, let's enter the username and password of the user, and if it is less than 18, then it should throw an exception. Well, I created a user class with a constructor and getters. All code is below (Pay no attention to other methods)

public static void main(String[] args) throws UserNotFoundException, AccessDeniedException{
        Scanner scanner = new Scanner(System.in);

        System.out.println("Введите логин: ");
        String login = scanner.nextLine();
        System.out.println("Введите пароль: ");
        String password = scanner.nextLine();

        //TODO Проверить логин и пароль
//        User user = getUserByLoginAndPassword(login, password);
//        System.out.println("User: " + user.getLogin() + " - " + user.getEmail());
//        System.out.println("Access granted");
        //TODO Вызвать методы валидации пользователя

    }
    
    public static User[] getUsers(){
        User user1 = new User("john", "[email protected]", "pass", 24);
        User user2 = new User("mike", "[email protected]", "qwerty", 22);
        User user3 = new User("steve", "[email protected]", "asdfg", 23);
        return new User[]{user1, user2, user3};
    }

    public static User getUserByLoginAndPassword(String login, String password) throws UserNotFoundException{
        User[] users = getUsersList();
        for (User user : users) {
            if(login.equals(user.getLogin()) && password.equals(user.getPassword())){
                return user;
            }
        }
        throw new UserNotFoundException("User not found: " + login);
    }

    private static User[] getUsersList() {
        return getUsers();
    }


    public static void validateUser(User user) throws AccessDeniedException{
        if(user.getAge()<18){
            throw new AccessDeniedException("Access Denied");
        }else{
            System.out.println("Age access granted");
        }
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
gsaw, 2021-02-02
@gsaw

Strange question of course, but probably so

try {
    validateUser()
    System.out.println("Проходите")
} catch( AccessDeniedException e) {
    System.out.println("Не положено!")
}

D
Denis Zagaevsky, 2021-02-03
@zagayevskiy

You don't have to do that at all. You can't build business logic on exceptions. Throwing an exception is a very expensive operation. And therefore it must be exceptional, that is, not normal for the program to work.
The validation method must return a validation error code (in the simplest case - true / false, in a more complex one - enum { OK, AGE_DENIED, PERMISSION_DENIED, ....}, in a complex one - an object with additional fields (in Java, just sealed classes Higher
up the stack (in your case - in main) there should be a check and already a reaction, prints, etc. The validation method itself should not print anything
. get away from static something like this:

class App {
    public static void main (args){
         new App(args).run();
    }

    private  void run(args) { 
          //.... твой код
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question