Try / Catch in Constructor - Recommended Practice?

后端 未结 3 965
我在风中等你
我在风中等你 2020-12-05 10:06

Something I\'ve always been curious of

public class FileDataValidator {

private String[] lineData;

public FileDataValidator(String[] lineData){

    this.l         


        
3条回答
  •  萌比男神i
    2020-12-05 11:02

    You should consider the static factory pattern. Make your all-arguments constructor private. Provide a static FileDataValidator(args...) method. This accepts and validates all the arguments. If everything is fine, it can call the private constructor and return the newly created object. If anything fails, throw an Exception to inform the caller that it provided bad values.

    I must also mention that this: catch (Exception e) { printSomeThing(e); }

    Is the deadliest antipattern you could do with Exceptions. Yes, you can read some error values on the command line, and then? The caller (who provided the bad values) doesn't get informed of the bad values, the program execution will continue.

提交回复
热议问题