How do you handle huge if-conditions?

后端 未结 21 1732
一向
一向 2021-01-31 17:14

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, u

21条回答
  •  情歌与酒
    2021-01-31 17:33

    Well, first off, why not:

    if (var1 && var2 && var2 && var3 && var4 && var5 && var6) {
    ...

    Also, it's very hard to refactor abstract code examples. If you showed a specific example it would be easier to identify a better pattern to fit the problem.

    It's no better, but what I've done in the past: (The following method prevents short-circuiting boolean testing, all tests are run even if the first is false. Not a recommended pattern unless you know you need to always execute all the code before returning -- Thanks to ptomato for spotting my mistake!)

    boolean ok = cond1;
    ok &= cond2;
    ok &= cond3;
    ok &= cond4;
    ok &= cond5;
    ok &= cond6;

    Which is the same as: (not the same, see above note!)

    ok = (cond1 && cond2 && cond3 && cond4 && cond5 && cond6);

提交回复
热议问题