javaparametersuser-inputinputverifier

Should user input verification be done at class level or UI level?


Say you have a console application with:

Main.java and ClassA.java

Your main class contains the public static void main(String[] args) method where you run your program, and it uses user input as arguments to call on methods in ClassA.

Do you put user input verification in the main method before sending the arguments to ClassA methods?

OR

Do you put user input verification in the ClassA methods which would relay a message back indicating successful input or not? Or throw a exception?

i.e. Integer.Parse(...) throws NumberFormatException when given an invalid input.


Solution

  • You might want to throw meaningful exceptions in classA and let your main method decide if/how to handle those exceptions. When you reuse class A, the new caller might want to make other decisions.

    I recommend the chapter "ErrorHandling" of the Book CleanCode (Robert C. Martin). It says for example "Define the normal flow", "Use Exceptions rather than return codes", "Separate your business logic and your error handling".

    In some cases it is important to get fast feedback... not wait two hours for a calculation to be finished and get an exception at 90 %. In other cases it is more important to get detailed feedback. Also see Data validation: fail fast, fail early vs. complete validation

    Check if it easy to read your code and to understand the normal flow. Each function should only do one thing/model one level of abstraction. Exception handling is one level ob abstraction.