[英]Is there a way to write this “if” list in a more elegant way?
假设我有一个对象POJO样式,并且对于它的某些属性,我必须检查是否等于特定值。 如果是这样,我必须将此属性添加到列表中并引发异常(如果其中一个属性等于特定值,则仅抛出一次)。 有没有比这更好的方法呢?
// pseudocode
List<String> list = new ArrayList<String>();
boolean haveToThrowException = false;
if (object.getAttributeA().equals(“0”) {
list.add(object.getAttributeA());
haveToThrowException = true;
}
if (object.getAttributeB().equals(“0”) {
list.add(object.getAttributeB());
haveToThrowException = true;
}
if (object.getAttributeC().equals(“0”) {
list.add(object.getAttributeC());
haveToThrowException = true;
}//and so on
if (haveToThrownException) {
throw new Exception(list.toString());
}
您可以这样做:
List<String> list =
Stream.of(object.getAttributeA(), object.getAttributeB(), object.getAttributeC())
.filter("0"::equals)
.collect(toList());
if (!list.isEmpty()) {
throw new Exception(list.toString());
}
您可以在临时列表或字符串或其他数据持有人中获取属性的值,然后在一个IF语句中检查该持有人是否包含不需要的值。 我的猜测是,您不希望接收带有不希望有的值的列表,但是您对不希望有的值的出现次数感到不确定:
//Java 9 syntax of list.of
List<String> allValues = List.of(object.getAttributeA(),object.getAttributeB(),object.getAttributeC());
//frequency will give you the number of occurences.
int numberOfOccurences = Collections.frequency(allValues , undesiredString);
if (numberOfOccurences > 0) throw new Exception(undesiredString + " : " + numberOfOccurences );
根据第一个答案,您还可以执行以下操作:
Stream.of(object.getAttributeA(), object.getAttributeB(), object.getAttributeC())
.filter("0"::equals)
.reduce((var1, var2) -> var1 + var2)
.ifPresent(string -> {
throw new RuntimeException(string);
});
看来您根本不需要。
是? 我认为在这种情况下, 策略模式会非常有效。
该解决方案比其他解决方案具有更多的代码,但是,如果您将来需要检查更多属性,则具有不更改调用类的优点。
这是一些伪代码...
public class ThrowsException {
private Strategy strategy;
public ThrowsException(Strategy strategy) {
this.strategy = strategy;
}
public void doYourMethod(Object object) {
List<String> values = this.strategy.checkObject(object);
if (!values.isEmpty) {
throw new Exception(values.toString());
}
}
}
一类会迭代各个策略的类,以使调用类不知道可以有多个策略。
public class ForLoopStrategy implements Strategy {
private List<CheckObjectStrategy> strategies
public ForLoopStrategy(List<CheckObjectStrategy> strategies) {
this.strategies = strategies;
}
public List<String> checkObject(Object object) {
List<String> values = new ArrayList<>();
for (CheckObjectStrategy strategy : this.strategies) {
String value = strategy.checkObject(object);
if (value != null) {
values.add(value);
}
}
}
}
将检查特定属性的实际类。 您要检查的每个属性都需要一个。
public class CheckAttributeA implements CheckObjectStrategy {
public String checkObject(Object object) {
String value = null;
if (object.getAttributeA().equals("0")) {
value = object.getAttributeA();
}
return value;
}
}
顺便说一句,我敢肯定,如果您可以使用反射来调用不同的属性,那么这里有些简单的事情……
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.