Need help to write - null check for objects

19 views
Skip to first unread message

Renee T

unread,
Nov 12, 2014, 3:27:24 AM11/12/14
to check...@googlegroups.com
Dear All,
 
I need your help to write the below custom rule. I need a null check rule for an object, before we retrieve values from an object.
 

eg:
Class Foo{

int A;
String B;
.
.
}

if (foo.getA() > 5){
}

If any operation is done on the object without a null check, it has to be highlighted and logged..
Thanks in anticipation!

Roman Ivanov

unread,
Nov 12, 2014, 10:08:13 PM11/12/14
to Renee T, check...@googlegroups.com

Please write exact and compilable code as examples. Please provide example of code that you think is correct and few codes that are not correct. In each incorrect example please write trailing single line comment. Also provide message you thinks is appropriate.

Thanks,
Roman Ivanov

--
You received this message because you are subscribed to the Google Groups "checkstyle" group.
To unsubscribe from this group and stop receiving emails from it, send an email to checkstyle+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Renee T

unread,
Nov 25, 2014, 8:51:12 AM11/25/14
to Roman Ivanov, check...@googlegroups.com
Hi,
 
PFB example:
 
public class Foo{
  int A;
  public int getA() {
    return (5);
  }

public void check(){
 Foo foo = new Foo();
 Foo bar = new Foo();
 
    // missing null check should show a violation
    if (foo.getA() > 5){ }
    // missing null check should show a violation
    if (bar != null && foo.getA() > 5) {}
    // correct null check
    if (foo != null && foo.getA() > 5) { }
  }
}
 
Thanks.

Roman Ivanov

unread,
Nov 29, 2014, 1:04:00 AM11/29/14
to Renee T, check...@googlegroups.com
Hi Renee,

please be aware that Checkstyle can not distinguish types , and does not aware about their hierarchy. All you have is tree of String values.

so you need to listen in Check specified by you type creation ("new" operator) or method parameters.
After that traverse tree below yourself and search for variable usage and detect "variable != null".

Just take a look at other Checks for examples how it it possible to be done. 

thanks,
Roman Ivanov
Reply all
Reply to author
Forward
0 new messages