我有一个
$total
和A
$balance
. 余额不能大于总数,但两者都可以是负数。基本上,我是想看看余额是否在零和总数之间。
所以,
if (($total < 0 && $balance < $total) || ($total > 0 && $balance > $total)) {
/** BAD **/
}
if (between($total < 0 ? $total : 0, $total < 0 ? 0 : $total, $balance) {
/** BAD **/
}
当然有两种方法可以实现这一点,但是这里有没有一种方法可以减少逻辑量呢?一些“聪明”的数字理论,我相信我应该知道…但是不要。
我正在使用PHP,但是比较的原则应该从任何语言/算法中转换出来。
意见反馈
如果合计为负,则余额必须为负且不小于合计。
如果合计为正,则余额必须为正且不大于合计
也许一张照片会有帮助!
Balance : BAD | Allowable -ve balances | Allowable +ve balances | BAD
Total : -5 .. -4 .. -3 .. -2 .. -1 .. 0 .. 1 .. 2 .. 3 .. 4 .. 5
进一步反馈
在这个问题上,“余额永远不能大于总数,但两者都可以是负数”…我说的是数量,而不是价值。我想我没有说清楚:
https://study.com/academy/lesson/what-is-magnitude-definition-lesson-quiz.html
解决方案
根据提供的意见。
<?php
class RangeTest extends \PHPUnit\Framework\TestCase
{
/**
* @param int $balance
* @param int $total
* @param bool $expected
*
* @dataProvider provideRangeValues
*/
public function testRange(int $balance, int $total, bool $expected)
{
$this->assertEquals((($total / abs($total)) * ($total - $balance) >= 0), $expected);
}
public function provideRangeValues()
{
return
[
'Positive Balance = Positive Total' => [10, 10, true],
'Positive Balance < Positive Total' => [5, 10, true],
'Positive Balance > Positive Total' => [10, 5, false],
'Negative Balance = Negative Total' => [-10, -10, true],
'Negative Balance < Negative Total' => [-5, -10, true],
'Negative Balance > Negative Total' => [-10, -5, false],
];
}
}