开发者

Vim script to insert Java null reference checks for chained method calls

开发者 https://www.devze.com 2022-12-20 14:09 出处:网络
I want to write avim script to do the following: if I have the following in my Java code, Z z = obj1.foo().bar().foo1().bar1()

I want to write a vim script to do the following:

if I have the following in my Java code,

Z z = obj1.foo().bar().foo1().bar1()

it should be replaced by

if(obj1 != null) {  
  T1 o1 = obj1.foo();  
  if(o1 != null) {  
    T2 o2 = o1.bar();  
    if(o2!=null) {  
      T3 o3 = o2.foo1();  
      if(o3 != null) {  
         z = o3.bar1();  
      }  
      else   
         z = null;  
    }  
    else   
         z = null;  
  }  
  else  
     z = null;  
}  
else   
  z = null  

I want to write a vi command that takes as arguments a comma-separated list of Types T1,T2 ... and so on to give me this big thing.

开发者_如何学JAVA

How do I learn about vimscripting?


Like those who have commented on your question, I believe there is a better way to deal with your problem.

Here are my concerns with your idea:

  • That code isn't very readable; it will make it more difficult and effort-intensive to debug or enhance your code in the future
  • Your approach will make adjustments even in cases where a null reference is impossible
  • There may be circumstances in your code where returning null is inappropriate; some of these may already be handled in a better way
  • I suspect a script like that will actually introduce bugs or compile-time errors; here's one example off the top of my head

    // Be sure to cal foo.bar().foobar() in special cases public Foo bar() { // do work... }

becomes...

// Be sure to cal if(foo != null) {
  Bar bar = foo.bar();
  if (bar != null) {
    Foobar foobar = bar.foobar();
    in special cases
  }
}
public Foo bar() {
  // do work...
}

Instead, use a static analysis tool (or more than 1) like FindBugs, which is really good at catching likely null pointer de-references.

0

精彩评论

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