What's the best practise when adapting C-style functions which return a true/false to Java?
Here's a simple method to illustrate where the problem lies.
public static boolean fileNameEndsWithExtension( String filename, String fileExtension) {
return filename.endsWith( fileExtension );
}
Note that there's probably a more elegant way of filtering files (feel free to comment on this). Anyway, if filename is a null
value, does one:
null
and the case where the String
or file name doesn't end with a given file extension? null
value. Exception
and force the programmer to make sure that a null
value is never passed to the method? You should throw a NullPointerException or an IllegalArgumentException if filename is null. I'll let you decide which is best. There's a good debate on which to use in the question: IllegalArgumentException or NullPointerException for a null parameter?
You do what makes sense in the problem domain of your particular application:
Most of the time, option 3 is going to be sensible, but no one here can rule out the applicability of the others to your application. If you pass a lot of meaningful null filenames around for a good reason, it might make sense to choose one of the others.
I would use either 1 or 3. Preferably I would throw NullPointerExceptions or atleast use an assert .
Returning nullable Booleans usually causes more trouble than they are worth, you have check for nulls etc. Besides fileNameEndsWithExtension()
looks like a function that you'll be using only when you know that you have a valid filename.
Also do not forget that fileExtension
might also be a null.
I would return false if filename is null, and not bother with the distinction between null and any other non-matching values.
If null filename is a distinct state that needs to be verified and handled specifically, then this should be validated separately, preferably before checking endsWith(), but still retain the null check in endsWith() to prevent unnecessary runtime exceptions.
The reason that I would choose the behaviour of null = false, is probably due to influence from relational databases. The following query would only return rows which match the condition, everything else (nulls and mismatches) would be ignored.
select * from filenames
where filename like '&fileExtension';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.