如何定义“ isValid”?有理有据 [英] how to define "isValid" function with reason
问题描述
我正在尝试在文件生成程序中的某些状态下建模
:
I am trying to model some states in my file generation program, at one point :
- 我要检查数据的当前状态
- 如果数据有效,我要继续
- 否则,我想通知用户无法继续的原因
伪代码如下:
if(isValid()){
writeFile()
} else {
switch(getReason()){
case FAIL1: doSomething1();
break;
case FAIL2: doSomething2();
break;
case FAIL3: doSomething3();
break;
}
}
不确定这种方法是否正确,像您的建议/意见。其中:总共有少于10个错误状态,并且在给定时间仅适用一个错误状态。
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.
推荐答案
来自加尔纳弗的想法正在朝着良好的方向发展;但是从面向对象的角度来看,它仍然不是一个很好的解决方案。
The idea from garnulf is going in a good direction; but it is still not a really good solution in OO terms.
事情是:您已经提到了重要的关键概念:状态,就像在状态机中一样。
Thing is: you already mentioned the key concept that is important here: state, as in state machine.
您真的想在这里使用多态性:
You really want to use polymorphism here:
abstract class Reason() {
String getMessage() { // just to show that there might be some shared code
abstract void doSomething();
然后,您的Reason类将具有不同的子类;最后,您的客户代码归结为:
Then you would have different subclasses for your Reason class; and in the end, your client code boils down to:
getReason().doSomething();
因为每个原因都知道该怎么做!当然,这可能需要进一步思考-取决于这些不同错误原因的真正原因。
Because each reason knows whats to do about itself! Of course, that might require some further thinking - depending on the fact what those different error reasons are really about.
关键点是:您真的想避免任何对枚举或字符串值的切换。如果有的话,您将这样的开关隐藏在工厂内部,这会返回一些抽象类/接口(工厂将在其中为您创建一个具体的子类/实现)。
The key point is: you really want to avoid any kind of switching over enum or string values. If at all, you hide such switches inside of factories, that return some abstract class / interface thingy (where the factory creates a concrete subclass/implementation for you).
这篇关于如何定义“ isValid”?有理有据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!