CollapsibleIfStatements

筅森魡賤 提交于 2019-12-05 09:42:54

One possibility is to factor out the repeated obj.getSomething() and then collapse the nested if statements:

for (SomeObject obj : getSomeObjects()) {
  Something smth = obj.getSomething();
  if (!smth.isEmpty() && !list.contains(smth)) {
      list.add(smth);
  }
}

To my eye, the result is quite readable, and should no longer trigger the PMD warning.

An alternative is to replace the List with a Set, and avoid the the explicit contains() checks altogether. Using a Set would also have better computational complexity.

I think this is what PMD wants:

if (!obj.getSomething().isEmpty() && !list.contains(obj.getSomething())) {
  list.add(obj.getSomething());
}

Here are few tips for improvements (and preventing PMD to scream):

  1. Extract variable:

    final Something sth = obj.getSomething();
    if (!sth.isEmpty() && !list.contains(sth)) {
      list.add(sth);
    }
    
  2. Extract method in Something (much more OOD):

    class Something {
    
        public void addToListIfNotEmpty(List<Something> list) {
            if(isEmpty() && list.contains(this)) {
                list.add(this);
            }
        }
    
    }
    

    and replace the whole condition with simple:

    obj.getSomething().addToListIfNotEmpty(list);
    

It is collapsible:

if (!obj.getSomething().isEmpty() && !list.contains(obj.getSomething())) {
    list.add(obj.getSomething());
}

IMHO, this check can be useful sometimes, but should be ignored in some other cases. The key is to have code as readable as possible. If you feel that your code is more readable than a collapsed if statement, then add a @SuppressWarnings("PMD.CollapsibleIfStatements") annotation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!