簡體   English   中英

有沒有一種方法可以更優雅地編寫此“ if”列表?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM