重构条件 [英] Refactor a condition

查看:92
本文介绍了重构条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a,b,c,d,e,f,g类型为unsigned int的条件如下:

There is a condition for a,b,c,d,e,f,g of type unsigned int given as follows:

if ((a > 0) and (b < a) and (c >= d))
{
    return ((e < std::min(std::max(0, a - g), b)) and 
            (f < std::min(d, std::max(0, c - g))));
}

我正在寻找重构表达式以使其更具可读性的方法。

I am looking for the way of refactoring the expression to make it more readable.

推荐答案

优化是错误的术语,但是可以重写代码以找到更好的(对业务进行了简化或精简)

Optimization was the wrong term, but the code can be rewritten to find a better (more reduced, or succinct to the business) logic.

X < min(Y, Z)    <=>    X < Y and X < Z
X < max(Y, Z)    <=>    X < Y or X < Z            (less usefull)

然后可能的重写是

return ((e < std::min(std::max(0, a - g), b)) and 
        (f < std::min(d, std::max(0, c - g))));

return ((e < std::max(0, a - g) and e < b)) and 
        (f < d and  f < std::max(0, c - g))));

return (e < 0 or e < a - g)
       and e < b
       and f < d
       and (f < 0 or f < c - g);

根据其他约束,这可能是可简化的。

Depending on other constraints this might be reducable.

我宁愿在函数之间来读取最小和最大。

I would rather make a function between for the hard to read min+max.

return e < minmax(b, a - g, 0) and 
       f < minmax(d, c - g, 0);

由于maxmin也是可行的,我没有在这两者之间调用。

I did not call this between, as maxmin is feasible too.

已添加

Added

@Jarod向我指出了一个事实,即OP提到的所有数字都是 unsigned 。然后

@Jarod pointed me to the fact, that the OP mentioned all numbers would be unsigned. Then

max(a - g, 0)

大概应该是

a > g ? a - g : 0

这篇关于重构条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆