Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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;
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...