如果可能,重新构建if else条件

时间:2014-01-16 01:06:16

标签: java if-statement

我需要一些帮助来重新构建我在程序中的if-else条件。这是一个微不足道的问题,但我一直在长时间工作,似乎无法找到一个好的解决方案。

如果我必须说明这些条件:

 This method should be executed for type 'A' objects iff `newValue` is 0, 
 otherwise it should be run only for type 'B' objects.   

我想避免使用此代码中的嵌套ifs。

 public static void someMethod(final Object object) {

    if (MyObjects.getType(object) == ObjectType.A) {
        if (newValue != 0) {
            throw new IllegalStateException("newValue for A can only be 0");
        }
    } else if (MyObjects.getType(object) != ObjectType.B) {
        throw new IllegalStateException("Invalid object type received.");
    }

    // More code here
 }

4 个答案:

答案 0 :(得分:0)

如果您只需删除内部if,则将newValue != 0添加到第一个条件..

public static void someMethod(final Object object) {

   if (MyObjects.getType(object) == ObjectType.A && newValue != 0) {
           throw new IllegalStateException("newValue for A can only be 0");
   } else if (MyObjects.getType(object) != ObjectType.B) {
       throw new IllegalStateException("Invalid object type received.");
   }

   // More code here
}

这是你想要做的吗?

答案 1 :(得分:0)

if ((MyObjects.getType(object) == ObjectType.A) && (newValue != 0)) {
        throw new IllegalStateException("newValue for A can only be 0");
} else if (MyObjects.getType(object) != ObjectType.B) {
    throw new IllegalStateException("Invalid object type received.");
}

答案 2 :(得分:0)

 public static void someMethod(final Object object) {

    if ((object instanceof A && newValue==0)) || object instanceof B) {
        //then execute.
    }

 }

答案 3 :(得分:0)

public static void someMethod(final Object object) {

    if ((MyObjects.getType(object) == ObjectType.A && newValue != 0) || (MyObjects.getType(object) != ObjectType.B)) {
            throw new IllegalStateException("newValue for A can only be 0 OR Invalid object type received.");
        }
    // More code here
 }