You typically find such checks done at the beginning of public methods to validate the arguments passed to the method (pre-conditions that need to be fulfilled in order that the method may execute meaningfully). Usually the method throws an IllegalArgumentException if the arguments are not as expected.
I think this approach is called 'Programming by Contract'. The users of the method are expected to know what are 'valid' arguments (usually specified in the javadoc) and since a RuntimeException is thrown the caller does not need to handle it.
nice to see the inputs, but I pretty well know the usage of it....but I was rather looking for some answers that would highlight the need for such syntax rather than the standard human readable coding? as suggested by adeel that is
Are you just asking why someone would put the "null" first, instead of the variable? There's no technical reason at all for doing this. Someone may have an argument for why they like it stylistically, but I think most folks would agree with you that putting the variable first is nicer.
The style where a null or literal is put first in an expression is a C/C++ idiom. Its purpose is to avoid subtle logic errors involving the incorrect use of the = operator where use of == is intended. For example:
This comes about as, in C/C++, the result of an expression is treated as false if it evaluates to zero and as true if non-zero. In Java the result of such an expression must be a boolean or the code will not compile. This type of compilation error is a right royal PITA as I have found to my cost on more than one occasion in the past! Happily not since making the transition to Java.
An analogue of this type of style in Java is the comparison of a string object to a literal with the equals() method:
Joined: Aug 15, 2004
i have never thought if it. its really simple it never comes into my mind buddy. wht i used to do is make a utility function like,
String getAbsoluteString(String string);
which returns me empty string when there is null.
thanx again jules
[ September 13, 2004: Message edited by: adeel ansari ] [ September 13, 2004: Message edited by: adeel ansari ]
Thanks a lot for your valuable input julian and adeel.
Adeel : what you said also makes sense, but what if I really want to check if a String is null? your String.equals says true or false if you are checking the Absolute Value.... More often than not I would check if the input Variable is null or not could have a greater impact on the overall system. Your suggestion is best if you are bothered if the input String is "something"...but imagine if there are more strings to be compared (which is generally the case)....then you would probably run the whole routine before you go ahead with the reporting of that result rather at the first instance of checking if the string is null and immediately returning.