HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Ternary gate handling - more succinct way then a bunch of if statements

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
handlingstatementsmorewayternarybunchsuccinctthengate

Problem

I have classes representing gates (OR, XOR, AND etc) with the following method that is called whenever a property changes.

Here is the XORGate code:

public void computeOutput() {
        if (this.input1 != null && this.input0 != null) {
            if (this.input0.getValue() || this.input1.getValue()) {
                if (this.input0.getValue() && this.input1.getValue()) {
                    this.output.setValue(false);
                }
                else {
                    this.output.setValue(true);
                }

            } else {
                this.output.setValue(false);
            }
        }
        else {
            this.output.Value = false;
        }

    }


It's horrible, but I can't think of a nicer way. It works as follows:

If any of the inputs are null, treat the output as false. If any of the inputs are true BUT not all of the outputs are true (i.e just one is true), set the output to true. If BOTH input terminals are true, output is false. And finally, if none of the input is true, output is false.

Very basic stuff.

Solution

public void computeOutput() {
    output.setValue(
            (input1 == null || input0 == null)
            ? false
            : (input0.getValue() ^ input1.getValue()));
}

Code Snippets

public void computeOutput() {
    output.setValue(
            (input1 == null || input0 == null)
            ? false
            : (input0.getValue() ^ input1.getValue()));
}

Context

StackExchange Code Review Q#4729, answer score: 4

Revisions (0)

No revisions yet.