Say my comparator function fooaccepts a time sequence as an input, which can be a series of time from small to large or from large to small.
foo might look like this:
Foo(List<double> timestampList) {
if (currentTime > previousMaxValueTimestamp) {
...
} else if (curremtTime > previousMinValueTimestamp) {
...
}
}
The above works for direct sequence, but not vice versa. How can I elegantly write logic that works for both types of sequences? Below I want to do this, but it duplicates most of the code, which is undesirable.
Foo(List<double> timestampList, boolean isForward) {
if (isForward) {
if (currentTime > previousMaxValueTimestamp) {
...
} else if (curremtTime > previousMinValueTimestamp) {
...
}
} else {
if (currentTime < previousMaxValueTimestamp) {
...
} else if (curremtTime < previousMinValueTimestamp) {
...
}
}
}
My current solution is similar to below. Is this a good coding style?
Foo(List<double> timestampList, boolean isForward) {
if ((isForward && currentTime > previousMaxValueTimestamp) || (!isForward && currentTime < previousMaxValueTimestamp)) {
...
} else if ((isForward && curremtTime < previousMinValueTimestamp) || (!isForward && currentTime > previousMaxValueTimestamp)) {
...
}
}
source
share