假设我的比较器函数foo采用时间序列作为输入,这可能是从小到大,或从大到小的一系列时间.
Foo可能看起来像这样:
Foo(List timestampList) {
if (currentTime > previousMaxValueTimestamp) {
...
} else if (curremtTime > previousMinValueTimestamp) {
...
}
}
以上工作用于正向序列,但不适用于反向序列.我怎样才能优雅地编写适用于两种类型序列的逻辑?
下面是我想要做的,但它复制了大部分代码,这是不希望的.
Foo(List timestampList, boolean isForward) {
if (isForward) {
if (currentTime > previousMaxValueTimestamp) {
...
} else if (curremtTime > previousMinValueTimestamp) {
...
}
} else {
if (currentTime < previousMaxValueTimestamp) {
...
} else if (curremtTime < previousMinValueTimestamp) {
...
}
}
}
我目前的解决方案如下.编码风格好吗?
Foo(List timestampList, boolean isForward) {
if ((isForward && currentTime > previousMaxValueTimestamp) || (!isForward && currentTime < previousMaxValueTimestamp)) {
...
} else if ((isForward && curremtTime < previousMinValueTimestamp) || (!isForward && currentTime > previousMaxValueTimestamp)) {
...
}
}