On 9/21/2012 7:09 AM, Ben Engbers wrote:
Hi,
In my program, I know that at some moment the value of a variable X will
change from value 1 to value 2. I am not interested in the value of X
itself but the transition should trigger an event. Example, if the value
of a stock will reach a certain value, I want to sell but after that I'm
not interested in the value anymore (until it might reach another
break-value).
Of course I could program this as:
if oldvalue <= testvalue and newvalue > testvalue then
do something;
oldvalue = newvalue;
end
But suppose that there are a lot of variables that I need to watch and I
don't want to write a test for every one.
If the program does not test whether a transition occurred
for some variable, then the program follows the same path whether
the transition occurs or not -- that is, in the absence of a test
the program is oblivious to the transition.
There are probably a gazillion ways to arrange the pieces of
the tests, but no way to avoid making them.
Wat is the best strategy to watch the transition?
Insufficient information. A few issues that would probably
matter a lot in the choice of an approach:
- Are the variables "related" or "independent?" For example,
if X and Y have the same threshold and you know X is always
greater than Y, then if X is below the threshold you can
infer that Y is, too, and needn't make a separate test.
- How many transitions do you care about? If X rises above
its threshold, do you care whether it then falls below it
and rises again?
- If you care about multiple transitions, how do you want to
behave when X jiggles insanely in a narrow region containing
its threshold? Do you want a notification for every crossing,
or only the first until a "significant" later excursion, or
only the first until T seconds have elapsed, or ...?
- How is the overall program structured? Would you like to
write `if(var.transitioned())' at points of interest, or
would you like to "register an observer" to be notified of
transition events, or would you like transition events to
be queued when they occur and handled later, or what?
around all of the variable updates.
simple mutators, you can add your check directly after that update. Note