开发者

Java coding standards and multiple IF's

I have the following lines of code:

if(
    checker.this()==false ||
    checker.that()==false ||
    checker.what()==true||
    checker.cool()==false ||
    checker.damm()==true
开发者_运维技巧    (...)
  )
{
    option = Option.FALSE;
}

With about 20 checks that must be performed. I've found this to be the most 'visual-tolerable' form of writing this if with multiple OR sequence but I'm not yet satisfied. Is there a coding standard for this?

Thanks.


The closest thing to a coding standard around this is Steve McConnel, whose authoritative book "Code Complete" recommends that complex conditions are factored into their own method, even if they are only used once. This allows for the name of the method to descibe what is happening.

if (checkValid(checker)) {...}

private boolean checkValid(Checker checker) {...}

checkValid is not a good name, of course, and should be replaced with something more descriptive. In this particular case you may want to make the check method part of "checker" object.

You should also avoid "something==true" and "something==false", and use "something" and "!something". This process is helped if you give the boolean methods appropriate names, like "isOpen()", "isEmpty()", rather than "open()" and "empty()". "checker.isOpen() && !checker.isEmpty()" is perfectly clear to read.


foo==false should better be written with !foo

Possibly, you can move this big if in a separate method: if (checker.complexConditionMet()) or if (complexConditionMet(checker)). It will improve readability.


checker.this()==false can be replaced by !checker.this()


I have never heard of a coding standard for anything like this. Personally, I would group several ifs into a method taking readability into consideration. For instance if you have something like:

if (this || that || what || where || why || cool || wow){ ... }

You could replace it with:

if (pronouns() || questions() || exclamations()){ ... }


I'd try to find common meaning between any of the various checks, and create functions from them.

When bundled together to describe a certain discrete, meaningful state of affairs or requirement, this can make the code less magical, easier to read, easier to test.

i.e. something like this, which is a bit "magical"

if (a == "world" || b == "dolly" || c == 42 || murder()) {

}

can be rendered more readable by changing it to something more like this:

if ( canSayHello() || canMeanLife()) {

}
...

boolean canSayHello() {
  return a == "world" || b == "dolly"
}

boolean canMeanLife() {
  return c == 42 || murder();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜