The use case is this:
public void testMethod(String para1, String para2, String para3){
if(para1==null){
System.out.println("para1 cannot be null");
}
if(para2)...
}
As the check null code above, we will be repeating ourselvous on writing the same code to check every parameter. But we cannot really factor out a common method, say, checknull(String para), because we need to output the name of the parameter so the users know which one is wrong.
Maybe there is no way to do this in java I guess. Method parameter names should be gone after compile if I understand it correctly.
So, how do you guys usually address this problem?
It's put in the message. No other way to do it. And no, you can't get the variable name.
I suggest you consider using Java's assert feature, which is highly-underused. It can be quite concise too:
public void testMethod(String para1, String para2, String para3) {
assert para1 != null : "para1 is null";
assert para2 != null : "para2 is null";
assert para3 != null : "para3 is null";
}
You just need to enable assertions in the VM with the -ea parameter. That's another advantage: you can turn them on or off as a runtime option.
It should be noted that the above will generate an AssertionError, which is an Error (in the Java sense), so won't be caught by a catch (Exception e) block. So they should be used for conditions that really aren't recoverable or things that should never happen.
Generally if a user breaks the contract (by passing in a null when they shouldn't, for example) then an appropriate RuntimeException may be better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With