你如何处理巨大的条件? [英] How do you handle huge if-conditions?

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

问题描述

这是我用过的每种语言都有问题的东西,我有一个if语句,但条件部分有很多检查,我必须将它分成多行,使用嵌套的if语句或只是接受它是丑陋的继续我的生活。

It's something that's bugged me in every language I've used, I have an if statement but the conditional part has so many checks that I have to split it over multiple lines, use a nested if statement or just accept that it's ugly and move on with my life.

您是否还有其他方法可能对我和其他遇到同样问题的方法有用?

Are there any other methods that you've found that might be of use to me and anybody else that's hit the same problem?

示例,全部在一行:

if (var1 = true && var2 = true && var2 = true && var3 = true && var4 = true && var5 = true && var6 = true)
{

示例,多行:

if (var1 = true && var2 = true && var2 = true
 && var3 = true && var4 = true && var5 = true
 && var6 = true)
{

示例嵌套:

if (var1 = true && var2 = true && var2 = true && var3 = true)
{
     if (var4 = true && var5 = true && var6 = true)
     {


推荐答案

将条件分成几个布尔值,然后使用主布尔作为条件。

Separate the condition in several booleans and then use a master boolean as the condition.

bool isOpaque = object.Alpha == 1.0f;
bool isDrawable = object.CanDraw && object.Layer == currentLayer;
bool isHidden = hideList.Find(object);

bool isVisible = isOpaque && isDrawable && ! isHidden;

if(isVisible)
{
    // ...
}

更好的是:

public bool IsVisible {
    get
    {
        bool isOpaque = object.Alpha == 1.0f;
        bool isDrawable = object.CanDraw && object.Layer == currentLayer;
        bool isHidden = hideList.Find(object);

        return isOpaque && isDrawable && ! isHidden;
    }
}

void Draw()
{
     if(IsVisible)
     {
         // ...
     }
}

确保给出变量名称,指示意图而非比功能。这将极大地帮助开发人员维护您的代码...它可能就是您!

Make sure you give your variables name that actualy indicate intention rather than function. This will greatly help the developer maintaining your code... it could be YOU!

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

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