Reputation: 761
Is there any simple way to resemble a truth table in code? It has 2 inputs and 4 outcomes, as shown below:
My current code is:
private void myMethod(bool param1, bool param2)
{
Func<int, int, bool> myFunc;
if (param1)
{
if (param2)
myFunc = (x, y) => x >= y;
else
myFunc = (x, y) => x <= y;
}
else
{
if (param2)
myFunc = (x, y) => x < y;
else
myFunc = (x, y) => x > y;
}
//do more stuff
}
Upvotes: 5
Views: 589
Reputation: 186748
I suggest using an array, i.e.
// XOR truth table
bool[][] truthTable = new bool[][] {
new bool[] {false, true},
new bool[] {true, false},
};
...
private void myMethod(bool param1, bool param2, bool[][] table) {
return table[param1 ? 0 : 1][param2 ? 0 : 1];
}
Upvotes: 5
Reputation: 43896
To simplify your code you could use param1
and param2
as bits of a value indexing in a predefined array:
private void myMethod(bool param1, bool param2)
{
Func<int, int, bool>[] myFuncs = {
(x, y) => x > y,
(x, y) => x < y,
(x, y) => x <= y,
(x, y) => x >= y
};
int index = (param1 ? 2 : 0) + (param2 ? 1 : 0);
Func<int, int, bool> myFunc = myFuncs[index];
//do more stuff
}
But of course simplicity and readability is in the eye of the reader.
If both paramX
are false
, index
will be 0
. If both are true
, index
will be 3
etc...
Upvotes: 0
Reputation: 2341
public int myTest(bool a, bool b)
{
if(!b)
return 3;
return a ? 1 : 2;
}
Upvotes: 0