Adapting methods which return true/false - java

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:
Return a false if filename is null? If so, how does one go about distinguishing between the case where filename is null and the case where the String or file name doesn't end with a given file extension?
Change the return type to the wrapper class Boolean which allows a null value.
Throw an Exception and force the programmer to make sure that a null value is never passed to the method?
Use another solution?

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:
If it makes sense to say that the empty set of filenames ends with any extension, return true.
If it makes sense to say that the empty set of filenames ends with no extension, return false.
If it makes sense to say that no one should ever ask this question, let the code throw.
If it makes sense to have a three-values result, sure, use Boolean.
Or make a three-valued enum and return from THAT.
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.

return true IFF filename.endsWith( fileExtension )
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';

Related

What is the difference between Optional.ofNullable() and `Optional.of()

First of all, I know the difference between the two methods.
Optional.of : Used to ensure that there is no null, if null is entered, nullPointExcepction
Optional.ofNullable : may or may not be null. Used to respond flexibly.
So, if I add orElseThrow(() -> new NullPointerException("null data")) to this, will it end up being the same?
I want to throw an error with explicit content.
So I get Optional.ofNullable(data).orElseThrow(() -> new NullPointerException("null data")))
use it as Is this pointless behaviour?
Optional.of(data).orElseThrow(() -> new NullPointerException("null data")))
I think this is also possible, but I'm just using ofNullable() to make the code look consistent.
to sum it up,
In the end, if you add orElseThrow(nullPoint)
Are of or ofNullable the same result?
then rather
Is of.orElseThrow better?
to sum it up, In the end, if you add orElseThrow(nullPoint) Are of or ofNullable the same result?
No. To see this, simply look at the types.
public static <T> Optional<T> of(T value);
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)
throws X extends Throwable;
Optional.of returns an Optional<T>, where orElseThrow is going to leave you with a T. So Optional.ofNullable(x).orElseThrow(...) is really just a very roundabout
if (x == null) {
throw new NullPointerException(...);
}
You're not actually doing anything with the Optional, just making one and discarding it in a really verbose way. So if that's your intent, just do an explicit null check; there's no need at all for Optional.
Which raises the question of why we would use of or ofNullable. With the introduction of Optional, there are now two ways to represent the concept of "this value might not exist" in Java: null and Optional.empty(). People on the Internet will argue till the end of time about which is better and when you should use which one (I have strong opinions on this which I'll refrain from sharing here, since it's not what you asked), but the point is that there are two different ways to do it.
For the rest of this post, I'll borrow a bit of notation from Kotlin and write T? to mean "a T value which might be null". It's not valid Java notation, but it gets the point across. So if we want to represent "A T which may or may not exist" in Java, we can use either Optional<T> or T?.
If we want to go from T? to Optional<T>, that's what Optional.ofNullable is for. It says "If the thing is null, give me Optional.empty(); otherwise give me the thing in an Optional". To go the other way, we can use Optional.orElse(null), which says "If I have a T, give it to me, otherwise show me null". So now we have a way to convert between the two approaches. So what's Optional.of for?
You should view Optional.of as an assertion of sorts. If Java had nullable types like Kotlin, then the difference would be something like
public static <T> Optional<T> of(T value);
public static <T> Optional<T> ofNullable(T? value);
That is, ofNullable expects that its value might be null. of is already assuming that it's not. Optional.of should be thought of an assertion that the value you're giving it is not null. If that assertion fails, we throw NullPointerException immediately rather than letting errors propagate to other parts of the program. If you're calling Optional.of and recovering from the NullPointerException it throws[1], then you are doing something very wrong. That function is an assertion we were dealing with non-null data to begin with, and if that assertion fails then your program should fail immediately with a good stack trace.
It sounds like, based on your use case, you have a value that might be null. In that case, Optional.ofNullable makes sense; it's prepared to handle the use case. If you want to throw a custom exception, you should do a null check beforehand (since you're the one handling the null, not Optional) and then call Optional.of. Or, of course, you can just do an old-fashioned null check and not use Optional at all, if you're planning to extract it anyway with orElseThrow. Certainly, the pipeline Optional.ofNullable(value).orElseThrow(...) in one line would be a code smell.
[1] Note that I say "recovering from", not "catching". A nice top-level catch (Exception exc) which logs all errors is perfectly acceptable and generally a good idea in larger applications. But if you're doing catch (NullPointerException exc) { return 0; } or something like that then you need to reconsider which Optional method you should be using.
First of all, I know the difference between the two methods.
Optional.of : Used to ensure that there is no null, if null is
entered, nullPointExcepction
Optional.ofNullable : may or may not be null. Used to respond
flexibly.
There's a clear point of misunderstanding.
The purpose of Optional.of() is not "to ensure that there is no null". It is not meant to be used as an assertion that a value that was passed into it is non-null. For such a validation you can use Objects.requireNonNull(), it'll either throw an NPE, or will return you a non-null value.
In order to be on the same page, the first important thing you have to keep in mind is that optionals were introduced in the JDK for only one particular purpose - to serve as a return type. Any other cases when optional is utilized as a parameter-type, or a field-type, or when optional objects are being stored in a collection isn't considered to be a good practice. As well, as creating an optional just in order to chain methods on it or to hide a null-check is considered to be an antipattern.
Here is a couple of quotes from the answer by #StuartMarks, developer of the JDK:
The primary use of Optional is as follows:
Optional is intended to
provide a limited mechanism for library method return types where
there is a clear need to represent "no result," and where using null
for that is overwhelmingly likely to cause errors.
A typical code smell is, instead of the code using method chaining to
handle an Optional returned from some method, it creates an Optional
from something that's nullable, in order to chain methods and avoid
conditionals.
I also suggest you to have a look at this answer to the question "Should Optional.ofNullable() be used for null check?", also by Stuart Marks.
With all that being said, combination Optional.of().orElseThrow() is both wrong and pointless:
If provided data is null method of() will raise an NPE and orElseThrow() will not be executed (i.e. its exception will get never be fired).
You're abusing the optional by creating an optional object not in order to return a nullable variable wrapped by it, but to hide the null-check (take a look at the quote above). That obscures the purpose of your code. You can use Objects.requireNonNull() instead to throw an exception if the given value must not be null or requireNonNullElse() to provide a default value.
For the same reason, you shouldn't use Optional.ofNullable().orElseThrow() at the first place.
Optional is like a Box
You might think of optional is if it is a parcel. When you need to send something, you go to the post office (i.e. returning from the method), where the thing that has to be sent is being placed into a box. When somebody (i.e. the caller) receives the parcel, it is being immediately unpacked. That is the whole lifecycle of the box called Optional.
When, according to the logic of your application, an object required to be returned from the method should not be null - use Optional.of(). It'll either send a parcel successfully or will emphasize that there's a problem by raising a NullPointerException.
If the given object is nullable by its nature, i.e. null isn't an abnormal case, then use Optional.ofNullable(), it'll fire either a box containing the object or an empty box.
And the caller (i.e. method that invokes the method returning an optional) is the one who has to unpack the box using a variety of tools that optional provides like orElseThrow(), orElseGet(), ifPresent(), etc.

Should we always check each parameter of method in java for null in the first line?

Every method accepts a set of parameter values. Should we always validate the non-nullness of input parameters or allow the code to fail with classic RunTimeException?
I have seen a lot of code where people don't really check the nullness of input parameters and just write the business logic using the parameters. What is the best way?
void public( String a, Integer b, Object c)
{
if( a == null || b == null || c == null)
{
throw new RunTimeException("Message...");
}
.....business logic.....
}
The best way is to only check when necessary.
If your method is private, for example, so you know nobody else is using it, and you know you aren't passing in any nulls, then no point to check again.
If your method is public though, who knows what users of your API will try and do, so better check.
If in doubt, check.
If the best you can do, however, is throw a NullPointerException, then may not want to check. For example:
int getStringLength(String str) {
return str.length();
}
Even if you checked for null, a reasonable option would be throwing a NullPointerException, which str.length() will do for you anyways.
No. It's standard to assume that parameters will not be null and that a NullPointerException will be thrown otherwise. If your method allows a parameter to be null, you should state that in your api.
It's an unfortunate aspect of Java that references can be null and there is no way to specify in the language that they are not.
So generally yes, don't make up an interpretation for null and don't get into a situation where an NPE might be thrown later.
JSR305 (now inactive) allowed you to annotate parameters to state that they should not be given nulls.
void fn(#Nonnull String a, #Nonnull Integer b, #Nonnull Object c) {
Verbose, but that's Java for you. There are other annotation libraries and checkers that do much the same, but are non-standard.
(Note about capitalisation: When camel-casing words of the form "non-thing", the standard is not to capitalise the route word unless it is the name of a class. So nonthing and nonnull.)
Annotations also don't actually enforce the rule, other than when a checker is run. You can statically include a method to do the checking:
public static <T> T nonnull(T value) {
if (value == null) {
throwNPE();
}
return value;
}
private static void throwNPE() {
throw new NullPointerException();
}
Returning the value is handy in constructors:
import static pkg.Check.nonnull;
class MyClass {
#Nonnull private final String thing;
public MyClass(#Nonnull String thing) {
this.thing = nonnull(thing);
}
...
I don't see a great deal of point in doing this. You're simply replicating behaviour that you'd get for free the first time you try to operate on a, b or c.
It depends if you expect any of your arguments to be null - more precisely, if your method can still make a correct decision if some parameters are null.
If not, it's good practice to check for null and raise an exception, because otherwise you'll get a NullPointerException, which you should never catch, as its appearance always indicates that you forgot to check your variables in your code. (and if you catch it, you might miss other occurrences of it being thrown, and you may introduce bugs).
On the other hand, if you throw RunTimeException or some other custom exception, you could then handle it somewhere on the upstream, so that you have more control over what goes on.
Yes, public methods should scrub the input, especially if bad input could cause problems within your method's code. It's a good idea to fail fast; that is, check as soon as possible. Java 7 added a new Objects class that makes it easy to check for null parameters and include a customized message:
public final void doSomething(String s)
{
Objects.requireNonNull(s, "The input String cannot be null");
// rest of your code goes here...
}
This will throw a NullPointerException.
Javadocs for the Objects class: http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html
It depends on what your code is trying to do and the situation in which you want to throw an Exception. Sometime you will want your method to always throw an Exception if your method will not be able to work properly with null values. If your method can work around null values then its probably not necessary to throw an Exception.
Adding too many checked Exceptions can make for very convoluted and complicated code. This was the reason that they were not included in C#.
No, you shouldn't do that universally.
My preferences, in order, would be:
Do something sensible with the null. The sensible thing to do depends entirely on the situation, but throwing a custom exception should not be your first choice.
Use an assertion to check for null and test thoroughly, eliminating any situations in which null input is produced since - a.k.a bugs.
For public APIs, document that null isn't allowed and let it fail with an NPE.
You should never throw a runtime exception unless it is truly a fatal condition for the operation of the system, such as missing critical runtime parameters, but even then this is questionable as the system should just not start.
What are the business rules? Is null allowed for the field? Is it not?
In any case, it is always good practice to CHECK for nulls on ANY parameters passed in before you attempt to operate on them, so you don't get NullPointerExceptions when someone passes you bad data.
If you don't know whether you should do it, the chances are, you don't need to do it.
JDK sources, and Joshua Bloch's book, are terrible examples to follow, because they are targeting very different audiences. How many of us are writing public APIs for millions of programmers?

Java : "xx".equals(variable) better than variable.equals("xx") , TRUE?

I'm reviewing a manual of best practices and recommendation coding java I think is doubtful.
Recomendation:
String variable;
"xx".equals(variable) // OK
variable.equals("xx") //Not recomended
Because prevents appearance of NullPointerException that are not controlled
Is this true?
This is a very common technique that causes the test to return false if the variable is null instead of throwing a NullPointerException. But I guess I'll be different and say that I wouldn't regard this as a recommendation that you always should follow.
I definitely think it is something that all Java programmers should be aware of as it is a common idiom.
It's also a useful technique to make code more concise (you can handle the null and not null case at the same time).
But:
It makes your code harder to read: "If blue is the sky..."
If you have just checked that your argument is not null on the previous line then it is unnecessary.
If you forgot to test for null and someone does come with a null argument that you weren't expecting it then a NullPointerException is not necessarily the worst possible outcome. Pretending everything is OK and carrying until it eventually fails later is not really a better alternative. Failing fast is good.
Personally I don't think usage of this technique should be required in all cases. I think it should be left to the programmer's judgement on a case-by-case basis. The important thing is to make sure you've handled the null case in an appropriate manner and how you do that depends on the situation. Checking correct handling of null values could be part of the testing / code review guidelines.
It is true. If variable is null in your example,
variable.equals("xx");
will throw a NPE because you can't call a method (equals) on a null object. But
"xx".equals(variable);
will just return false without error.
Actually, I think that the original recommendation is true. If you use variable.equals("xx"), then you will get a NullPointerException if variable is null. Putting the constant string on the left hand side avoids this possibility.
It's up to you whether this defense is worth the pain of what many people consider an unnatural idiom.
This is a common technique used in Java (and C#) programs. The first form avoids the null pointer exception because the .equals() method is called on the constant string "xx", which is never null. A non-null string compared to a null is false.
If you know that variable will never be null (and your program is incorrect in some other way if it is ever null), then using variable.equals("xx") is fine.
It's true that using any propertie of an object that way helps you to avoid the NPE.
But that's why we have Exceptions, to handle those kind of thing.
Maybe if you use "xx".equals(variable) you would never know if the value of variable is null or just isn't equal to "xx". IMO it's best to know that you are getting a null value in your variable, so you can reasign it, rather than just ignore it.
You are correct about the order of the check--if the variable is null, calling .equals on the string constant will prevent an NPE--but I'm not sure I consider this a good idea; Personally I call it "slop".
Slop is when you don't detect an abnormal condition but in fact create habits to personally avoid it's detection. Passing around a null as a string for an extended period of time will eventually lead to errors that may be obscure and hard to find.
Coding for slop is the opposite of "Fail fast fail hard".
Using a null as a string can occasionally make a great "Special" value, but the fact that you are trying to compare it to something indicates that your understanding of the system is incomplete (at best)--the sooner you find this fact out, the better.
On the other hand, making all variables final by default, using Generics and minimizing visibility of all objects/methods are habits that reduce slop.
If you need to check for null, I find this better readable than
if (variable != null && variable.equals("xx")). It's more a matter of personal preference.
As a side note, here is a design pattern where this code recommendation might not make any difference, since the String (i.e. Optional<String>) is never null because of the .isPresent() call from the design pattern:
Optional<String> gender = Optional.of("MALE");
if (gender.isPresent()) {
System.out.println("Value available.");
} else {
System.out.println("Value not available.");
}
gender.ifPresent(g -> System.out.println("Consumer: equals: " + g.equals("whatever")));

Smarter setter? Good or Bad Idea?

In a GWT solution. (so this is java code that is then compiled to javascript).
There are of course some classes.
Is it a good idea to make the setter check for Null on a String field?
something like this
public void setSomeField(String someField){
if (null != someField)
this.someField = someField;
else
this.someField = String.Empty;
}
Is this a good or bad idea? On the one had it will make coding easier as i wont have to check for null , on the other hand it would make me probably forget that I have to do this for other strings.
Thoughts?
Thanks
I say if such a logic is needed in your application, the setter is the place to put it. The main reason to have a get/set wrap around a private var is to be able to put logic around the access.
To answer the question of to default or not to default:
In my application it made sence to have a set of properties fall back to string.empty for display reasons. Although people could argue that the view should then cover these possibilities and check for nulls and display nothing, it was a lot of bloat all over my pages to do a check on every property.
That's why I started implementing SafeXX properties. So say I had 'myObj.Name' that could possibly have a null value, there would also be a property 'myObj.SafeName' that caught the null in the getter and returned a string.empty in stead. The little naming convention gives away that it is not the regular getter.
Here's something to consider. Would you expect this unit test to pass or fail?:
yourClass.setSomeField(null);
assertNull(yourClass.getSomeField());
If you're changing the null value to an empty string and returning that in getSomeField, then the client now has to check two conditions when testing...a String and a null String. Not a big deal, but what happens if you've got twenty String properties in the class...you'd probably better try to be consistent amongst all of the setters, and if you're not then the reason should probably be more obvious than just the documentation saying so.
There are certain conventions around getters and setters; certain expectations. If I call a setter on an object, then I usually expect the getter to return what I set. I don't expect it to return some representation of what I passed in that is more convenient for the class to work with internally. I don't care about the internals of the class, and don't want to.
If null really should be changed to "" for a valid reason (for example, it might mean "I don't care" and the default could be ""), go for it(but document it).
Otherwise, like if you just caught a NullPointerException and are trying to fix it this way, don't do it. If callers use obviously invalid values, the exception should be raised as soon as possible so that the caller notices the problem and fixes it before it bubbles up to a catastrophic, unexplainable error in a probably completely unrelated component.
In general, it is not a good idea to check for null values because the caller (the one who invokes the setter) may really want to set the value to null.
Suppose you query for 'someField' with this:
select * from ... where someField is null
If you set it as the empty string, the query above would fail.
If you don't want a field set to null, then don't set it to null.
This can be a good idea if you have no control over the code doing the setting, but if you do, it better to fix the problem at the source rather than put in work arounds like this.
That is hard to answer. On the first look it seems to make the usage better because you don't have to check for null all the time. But you loose the quality of null that means nothing is assigned. If you do String.Empty you already have ambiguity if someone gave you a String.Empty as parameter. Maybe it doesn't matter.
I personally (if at all) wouldn't do it in the setter. Inside your class null should have a value of its own. If you are for convenience a getter
return (this.someField != null) ? this.someField: String.Empty;
will do. You would keep the null internally to deal with but the outside has a more convenient method.
Generally and personally speaking I wouldn't do it. It looks good at first and makes a lot of things harder at later time.

Why String.indexOf do not use exception but return -1 when substring not found?

Why String.indexOf do not use exception but return -1 when substring not found?
The purpose of this question is: when we start custom exception.
I believe avoid the need to return special error code is right design path.
What's your opinion?
As a rule of thumb, if the purpose of a method is to check for something, then the lack of that something shouldn't be an exception. If the method is assuming that something is true, then the absence of that something would be an exception. Thus "File.exists()" doesn't throw a FileNotFoundException, but "File.open()" does.
exceptions are for exceptional cases, when a string does not contain a letter, that's hardly exceptional, unless you are using it for some extreme case. If that's what you are doing, you can always choose to throw your own exception.
Last I heard on that was...
'You throw an exception when your
method is unable to do what it
promises to' - Jeff Richter CVC 2nd ed
IndexOf() promises you to return the index of the first occurrence of a char/string. It would have thrown an exception if it was unable to do its job for some reason. It did its job but didn't find the string and hence returns -1 to convey the not-found result.
File.Open() will throw a FileNotException for a non-existing filepath since it is unable to do what it promises .. i.e. open the specified file.
returning -1 is almost as horrible as throwing an exception. The correct way would be to use option type if language just supported it better. In normal situation where there is result, you wrap the result in object and return that. Otherwise you return an object representing the "not result" situation.
In call site you have to check which one was it; you can't just use the return value because of their super type, they have to be inspected via pattern matching.
In pseudo syntax:
class Option[a] = Some[a] | None,
where a is generic type parameter, Some represents a result with value and None non-result without value.
in indexOf case you would have:
Option[Integer] indexOf(char c) = {
if(found) return Some(index)
else return None
}
and you use that this way:
result = "uncle".indexOf('c')
result match {
Some(i) => System.out.println("index was: " + i);
None => System.out.println("no value");
}
If you omitted either Some or None from matching (which is kinda generalized switch), compiler would give you a warning.
Also because exceptions are expensive in terms of performance
Lots of good answers here. This is a design issue where pragmatism has taken precedence over following "rules". In this case, there are some conflicting "rules":
avoid using special values as return data (not self-documenting, requires developer to handle special value in a distinct way from other code)
vs.
don't throw exceptions during routine execution of code, only when something unexpected happens
I agree with this design decision. If you do not, however, you can always write your own code to check for the existence of a string before checking its index. Do not be a prisoner of your language, bend it to your will. Languages are meant to be tortured!
It's a lot easier to deal with checking for a -1 than catching an exception.
Aside from the arguments against exceptions in general, I would add that -1 can be a useful result from indexOf and lastIndexOf, not just a special value. For instance, to parse the filename from a string that may or may not contain a path:
String filename = arg.substring(arg.lastIndexOf('/') + 1);
While perhaps a contrived example, this would be a bit more cumbersome with exceptions.
I think that one has to throw an exception when something unexpected happens.
That said, a substring not found in a String is not that unexpected, can happen, it is a reasonable result.
I agree with you that one should try to avoid returning error codes, but in this case we have only two choices, string found or string not found.
Until the author of Java's string.indexOf tells us the actual history...
Let's suppose we had to design it from scratch, some obvious design constraints for this problem:
indexOf must return a numeric value, so that when a match is found, you know where it is
valid indexes are guaranteed to be always integers
array (and string) indexes are zero-based in Java
Java is strongly typed
the integer numeric types are signed in Java
Given those basic constraints, some possible choices for function return type the would be integer (ideally of a type large enough to represent the last index in the largest possible string), OR... Object (and perhaps return null to indicate not found). But in practice returning Object would be neither efficient nor user-friendly, due to the need to check its validity and cast before usage for the found case - so it's not really a viable option!
So let's go with an integer. Do we want to throw an exception if not found? Throwing exceptions has multiple problems of its own - creating exception objects and jumping to exception handlers can be quite inefficient, and writing try/catch blocks around indexOf calls is no fun either!
So let's say we've narrowed it down: it has to return a (signed) integer type, and not throw an exception. Now which integer value should it return to represent not found?
In order to allow searching in strings as large as possible, we should reserve all positive integers for usage as meaning successfully found. Conversely, none of the negative numbers is needed to represent a 'found' index, so all are potentially available to use as return codes representing 'not found'.
If we could have picked any negative number, to represent not found, or just said 'all negative return values mean not found' it would do the job... But would it be the best design?
What are some reasons to use -1 instead of other negative numbers? My favorite reasons are simply '-1 is easy for everyone to remember, and you can do exact equality tests on it'. (Instead of being forced to use inequalities and think about off-by-one problems like whether you want less-than or less-than-or-equal, and what value to compare with, zero or negative one)
I also sometimes admire Chris's reason that (paraphrasing) 'it works nicely with substring(foundIndex + 1)'.

Categories

Resources