choucavalier
choucavalier

Reputation: 2770

Represent simple conditional statements in Java

I'm working on a project in which I need to represent conditional statements on object attributes and [booleans|integers|float...] because I need to store the results of these conditions (whether they are true or false) so that I don't have to check them again in the future (there are many conditions, it's actually an optimization).

class Foo {
    public String getThing() {
        return this.thing;
    }
    private String thing;

    public int getBob() {
        return this.bob;
    }
    private int bob;
}

class Bar {
    public String getStuff() {
        return this.stuff
    }
    private String stuff;
}

Foo foo = new Foo();
Bar bar = new Bar();

Here I would like to store the condition that foo.thing != bar.stuff and the condition that foo.bob < 3. I would like to be able to store all 4 main operations <, >, ==, != (the objects compared will implement Java's Comparable interface).

I imagined I could store a conditional statement in a

Triplet<getAttr1(), Operator.[Equal|GreaterThan...], getAttr2()

(with an evalution function and where Operator is a class I would have defined)

The attributes could be stored as functions since the value of the attribute will always be given by its getter. Thing is I also want to compare with other types, like boolean, int, float...

How can I represent these conditional statements?

Upvotes: 2

Views: 1648

Answers (1)

David Ehrmann
David Ehrmann

Reputation: 7576

Consider using Expressions, e.g.

interface Expression<T> {
    public T evaluate();
}

class BinaryDoubleExpression implements Expression<Double> {
    DoubleExpression left, right;
    DoubleOperator operator;

    BinaryDoubleExpression(double left, double right, BinaryDoubleOperator operator) {
        this.left = left;
        this.right = right;
    }

    Double evaluate() {
        return operator.operate(left.evaluate(), right.evaluate());
    }
}

enum BinaryDoubleOperator {
    ...
    Double operate();
}

It's a way to model literals, unary, binary, and ternary operators, and support different types. Each implementation then knows how to evaluate itself, leading to a traversal of the expression's parse tree.

Upvotes: 3

Related Questions