I wasn't sure exactly what to call these situations, so I'll illustrate it.
If I have something like this in a method:
if (i <= 5)
doSomething();
else
doSomethingElse();
but I know that i
will never be less than or equal to 5 once it exceeds 5, it becomes unnecessary to continue checking the if-statement once it branches off the first time.
Is it a good idea to implement a strategy pattern in this case, to avoid redundant checks?
class strategy1 implements strategy {
Object obj; // stores a reference to the object that uses it
void run() {
if (i <= 5)
doSomething();
else {
obj.strategy = new strategy2(obj);
obj.strategy.run();
}
}
}
class strategy2 implements strategy {
void run() {
doSomethingElse();
}
}
and the object simply calls strategy.run()
I feel like this sacrifices some readability and simplicity for performance, but it also makes it clear that i
will not fall below 6 once it hits 6, which provides some more information than the if-statement alone did. Is there a better way?