如何使这个IF块更短?

时间:2018-06-26 17:42:38

标签: java

如何使这段代码更短,更简单?

if ((fBody.equals("block") && sBody.equals("ball")) || (fBody.equals("ball") && sBody.equals("block"))) // CODE
if ((fBody.equals("wall") && sBody.equals("bonus")) || (fBody.equals("bonus") && sBody.equals("wall"))) // CODE

以此类推。

2 个答案:

答案 0 :(得分:2)

我会将文字“ ball”,“ wall”等放入Enum中。

public enum ObjectType {

    BLOCK("block"),
    BALL("ball"),
    BONUS("bonus"),
    WALL("wall");

    private String objectType;

    ObjectType(String objectType) {
        this.objectType = objectType;
    }

    public String getObjectType() {
        return objectType;
    }

    public boolean equals(String body) {
        return objectType.equalsIgnoreCase(body);
    }
}

然后我将sBodyfBody配对。

public class Pair {

    private final String fBody;
    private final String sBody;

    public Pair(String fBody, String sBody) {
        this.fBody = fBody;
        this.sBody = sBody;
    }

    public String getfBody() {
        return fBody;
    }

    public String getsBody() {
        return sBody;
    }

    @Override
    public String toString() {
        return "Pair{" +
                "fBody='" + fBody + '\'' +
                ", sBody='" + sBody + '\'' +
                '}';
    }
}

然后,我将利用Java 8的Predicate并创建这样的谓词列表:

public final class Predicates {

    public static final List<Predicate<Pair>> PREDICATES =
            Arrays.asList(
                    isBlockBall(),
                    isBlockBall()
                    // add rest of your predicates
            );

    private Predicates() {
        // we do not need to instantiate this
    }

    public static Predicate<Pair> isWallBlock() {
        return p -> ObjectType.WALL.equals(p.getfBody())
                && ObjectType.BLOCK.equals(p.getsBody());
    }

    public static Predicate<Pair> isBlockBall() {
        return p -> ObjectType.BLOCK.equals(p.getfBody())
                && ObjectType.BALL.equals(p.getsBody());
    }
}

然后您可以按照以下步骤测试您的状况:

public class TestingPairs {

    public static void main(String[] args) {
        final String fBody = "block";
        final String sBody = "ball";
        Pair pair = new Pair(fBody, sBody);
        final Optional<Predicate<Pair>> conditionMet = PREDICATES.stream().filter(pairPredicate -> pairPredicate.test(pair))
                .findFirst();

        if (conditionMet.isPresent()) {
            // do your stuff
        }
    }
}

答案 1 :(得分:1)

您可以创建一个包含所有可能的“正确”对的列表,然后在其上循环:

class Pair {
    String sBody;
    String fBody;

    public String getsBody()
    {
        return sBody;
    }

    public String getfBody()
    {
        return fBody;
    }
}

boolean check(List<Pair> list, String sBody, String fBody) {
    for (Pair pair : list) {
        if (pair.getsBody().equals(sBody) && pair.getfBody().equals(fBody)) {
            return true;
        }
    }

    return false;
}

您当然仍然必须事先以某种方式填充此列表