views:

73

answers:

1

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.

How do I learn about vimscripting?

+2  A: 

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.

Drew Wills