Say my comparator function foo
takes a time sequence as input, which could be a series of time from small to large, or from large to small.
Foo
may look like this:
Foo(List<double> timestampList) {
if (currentTime > previousMaxValueTimestamp) {
...
} else if (curremtTime > previousMinValueTimestamp) {
...
}
}
The above works for forward sequence, but not the reverse one. How can I elegantly write a logic that works for both types of sequence? Below is what I want to do, but it duplicates most of the code, which is not desired.
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 like below. Is it good coding style?
Foo(List<double> timestampList, boolean isForward) {
if ((isForward && currentTime > previousMaxValueTimestamp) || (!isForward && currentTime < previousMaxValueTimestamp)) {
...
} else if ((isForward && curremtTime < previousMinValueTimestamp) || (!isForward && currentTime > previousMaxValueTimestamp)) {
...
}
}
I don't know if something like this will still satisfy you, but in this way you can still reduce more or less your structure and you will not get this inflated code
if (isForward ? currentTime > previousMaxValueTimestamp :
currentTime < previousMaxValueTimestamp)
{
} else if (!isForward ? currentTime < previousMaxValueTimestamp :
currentTime < previousMinValueTimestamp)
{
}
If you have the list sorted as i suspect you do, you can simply use an iterator :
ListIterator li = a.listIterator(a.size());
while(isForward ? li.hasPrevious() : li.hasNext()) {
nextItem = isForward ? li.previous() : li.next());
//do stuff
}
taken from here and then edited to fit your needs
if your items are not pre-sorted and you can live with the pre-sorting overhead, you may use Collections.sort(yourList,yourSpecialComparator) providing your own special comparator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With