Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

java - how to define "isValid" function with reason

I am trying to model some states in my file generation program, at one point :

  1. I want to check the current status of the data
  2. if data is valid I want to continue
  3. otherwise I want to inform the user of the reason why I cannot continue

A psudocode would be like:

if(isValid()){
    writeFile()
} else {
    switch(getReason()){
        case FAIL1: doSomething1();
            break;
        case FAIL2: doSomething2();
            break;
        case FAIL3: doSomething3();
            break;
    }
}

Not sure if an approach like this is correct, would like your advice/opinions. Where: in total there are less than 10 error states, and only one error state is applicable at a given time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would create a enum for your Reason and put all the specific information of your reason there. Then you can parametrize the doSomething method with the specific information from the reason. Sounds to me like this could be a String. With this approach it is much easier to extend your code. The code could look like :

if(isValid()){
    writeFile()
} else { Reason reason = getReason(); 
    doSomething(reason.getMessage());
}

With your enum Reason

enum Reason {
    REASON1("message1"), REASON2("message2")/* ... */;

    private String message;

    private Reason(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...