In an event handler I'm responding to the change of a value. I have access to the old value and the new value and want to do certain things depending on what the change is.
Each different outcome will do some combination of actions/functions X, Y, or Z. Z accepts a parameter between -1 and 1. Order of performing these is not important.
Look at the following logic grid. The old value is the leftmost column of labels, and the new value is the top row of labels:
New:
0 !=0
-------- -------
Old: 0 | nothing Y, Z(1)
!=0 | X, Z(-1) X, Y -- Z(0) is okay but not required for this quadrant
What would be a good way to represent this?
I'm working in C# but will accept answers in any language since it's not really a language question—I can translate whatever.
Example:
if (oldvalue == 0 && newvalue == 0) return;
if (oldvalue != 0) X();
if (newvalue != 0) Y();
Z(oldvalue != 0 ? -1 : 0 + newvalue != 0 ? 1 : 0);
I suppose that looks pretty good, but there are other ways it could be done.
int which = (oldvalue == 0 ? 0 : 1) + (newvalue == 0 ? 0 : 2)
switch (which) {
case 1:
X(); Z(-1);
break;
case 2:
Y(); Z(1);
break;
case 3:
X(); Y();
break;
}
This is actually a slightly simpler case than what I'm dealing with. In the case that oldvalue and newvalue are nonzero and equal to each other, treat newvalue as if it was 0.
Feel free to answer as given or with this additional constraint. There's still a little bit more but I think it's too much to start off with. If things seem interesting afterward, I'll present the rest either here or in a new question.
I guess I'm asking the question because I end up with these logic grid things often, and they aren't always 2x2, sometimes they're a bit bigger. It's nice to notice that I can handle some responses with entire "stripes" like noticing that X is done every time the oldvalue != 0, but it seems like I'm starting to run into a pattern that begs for some expressive logic to handle it more generally instead of laboriously turning it into if then else statements. I mean, it would be really cool if I could provide a sort of grid of logic and let the compiler figure out the best way to handle it.
Just doing some wild brainstorming:
Conditions:
oldvalue == 0 ? 0 : 1
newvalue == 0 ? 0 : 2
Actions:
X = {false, true, false, true}
Y = {false, false, true, true}
Z(-1) = true where condition = 1
Z(1) = true where condition = 2
What are your ideas? I'll reward any material involvement at all.
See Question&Answers more detail:os