首页 新闻 赞助 找找看

java修改PMD出现的问题,大神们快来看看!!!!!!!

0
悬赏园豆:160 [已解决问题] 解决于 2016-12-16 11:47

代码如下:

public void contextDestroyed(final ServletContextEvent sce) {
        final ServletContext context=sce.getServletContext();
        context.removeAttribute("idlist");//这行提示“Potential violation of Law of Demeter (object not created locally)”请问各位如何修改?
}

ζั͡ޓއއއ๓ 堕落的主页 ζั͡ޓއއއ๓ 堕落 | 初学一级 | 园豆:5
提问于:2016-12-14 10:44
< >
分享
最佳答案
0

根据法则,这里你的context不是参数,不是当前对象,不是方法内实例化的对象,所以会提示这个。

这里我感觉应该再加一个方法

void contextRemove(ServletContext context,String name){

  context.removeAttribute(name);

}

然后再contextDestroyed方法内调用。

 

如果觉得这个规则太蛋疼可以排除掉。

收获园豆:160
Daniel Cai | 专家六级 |园豆:10424 | 2016-12-16 11:13

去掉是不可能的,  但是如果是用这种方法解决的话  代码量会不会太多了? 因为我出现很多这种问题

比如这种:if(!count.isEmpty()){ //那这行我该如何修改?

ζั͡ޓއއއ๓ 堕落 | 园豆:5 (初学一级) | 2016-12-16 11:19

我大概明白什么意思了!

ζั͡ޓއއއ๓ 堕落 | 园豆:5 (初学一级) | 2016-12-16 11:21

@ζั͡ޓއއއ๓ 堕落:

维基上的定义是这样的

More formally, the Law of Demeter for functions requires that a method M of an object O may only invoke the methods of the following kinds of objects:

  1. O itself
  2. M's parameters
  3. any objects created/instantiated within M
  4. O's direct component objects

这些规则如果要全遵守就别写代码了。

Daniel Cai | 园豆:10424 (专家六级) | 2016-12-16 11:26

@Daniel Cai: 好吧  我明白了  谢谢你了大神!

如果出现这种的“Potential violation of Law of Demeter (method chain calls)”  我是不是要拆分啊?

代码:request.getSession().setAttribute("count", MyHttpSessionListener.sessionCreated());

ζั͡ޓއއއ๓ 堕落 | 园豆:5 (初学一级) | 2016-12-16 11:33

@ζั͡ޓއއއ๓ 堕落: 对,因为这里你使用了request.getSession拿到的对象。而这个对象不是参数

Daniel Cai | 园豆:10424 (专家六级) | 2016-12-16 11:59

@Daniel Cai: 好的  知道了   谢谢  

ζั͡ޓއއއ๓ 堕落 | 园豆:5 (初学一级) | 2016-12-16 12:00

@ζั͡ޓއއއ๓ 堕落: 

public class Foo {
    /**
     * This example will result in two violations.
     */
    public void example(Bar b) {
        // this method call is ok, as b is a parameter of "example"
        C c = b.getC();
        
        // this method call is a violation, as we are using c, which we got from B.
        // We should ask b directly instead, e.g. "b.doItOnC();"
        c.doIt();
        
        // this is also a violation, just expressed differently as a method chain without temporary variables.
        b.getC().doIt();
        
        // a constructor call, not a method call.
        D d = new D();
        // this method call is ok, because we have create the new instance of D locally.
        d.doSomethingElse(); 
    }
}
Daniel Cai | 园豆:10424 (专家六级) | 2016-12-16 12:02
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册