Using double negatives to test for conditions - java

To validate user inputs, I am unsure of which of two alternatives is better
1
isNull( Object input )
2
notNull( Object input )
apache's commons lang library chose #2 but I am uncomfortable with double negatives. What do you say ?

To me, double negatives is always a bad thing.
I'd say stick to isNull. Checking for nullity then makes sense while reading.
The opposite would be
if (! isNull(o) )
// ...
which reads out "if not is null". Sure it sounds retarded read out loud, but it makes more sense than checking for nullity with option #1.
if (! isNotNull(o))
// ...
A statement which makes you rewind and say "hey, wait a minute... if not is not...".
But if there is a standard already with having negatives in method names, stick to it. Standards are good things, and should not be broken just because someone is "uncomfortable".

I am uncomfortable with functions which are longer than the code they replace.
I would use x == null or x != null. I agree that double negative isn't clear either.
A puzzle for you, when is (s != s) true? A good example of confusing behaviour. ;)

Honestly, I don't think it makes much difference.
If you are designing your own API, implement it the way you are most comfortable with. Indeed, there's no strong reason to not to implement both isNull and notNull if that makes you feel happier.
But I think it would be silly to abandon plans to use some third-party library solely because you are "uncomfortable with" double negatives. They really aren't that confusing.

The answer here depends on so many considerations, of which some are:
What does your programming environment support most naturally?
What does other similar code in the same project do?
What coding standards are you working to, if any?
Which approach is easier to understand for others reading your code?
If you want a more considered answer, do let us know some more of the details. In the meantime, my top tip would be to go for whatever enhances readability of the code: you want to give future maintainers as much help as you can.

I am a little confused by the question. If the methods in question are just returning a boolean depending upon whether the argument is null, then == null or != null are much better.
However, the reference to Apache Commons Lang seem to indicate that this is validity checking, and an appropriate exception should be thrown is the reference is null. In that case you can't invert the output easily.
FWIW, it looks as if JDK7 will introduce a notNull method, as discussed on an appropriate mailing list, something along the lines of:
public static <T> T notNull(T obj)
Used as:
import static java.util.Object.notNull;
public final MyClass {
private final Thing thing;
public MyClass(Thing thing) {
this.thing = notNull(thing);
}
...

Related

Difference between !(a==b) and a!=b

Last week in high school my IT teacher gave us a programm, where one part she wrote interested me a lot.
In an if-statement, she checked if an element of an array was not null, so the programm could proceed with this element, therefore she wrote:
if (!(array[i] == null), which confused me, because with this method you are just using a bracket more, which makes it less easy to read. I changed it to ìf (array[i] != null) and it worked just fine. But now I am confused, because as a teacher I assume you know a lot of your subject, so could there be a good reason why she used her method over mine? Is there some detail I don't know about?
There is no difference in the semantics of the two expressions. I would say there is no good reason to ever write the former.
But now I am confused, because as a teacher I assume you know a lot of your subject, so could there be a good reason why she used her method over mine?
The best thing to do is to ask your teacher. The most important thing to remember about teachers - as human beings - is that they have experiences, prejudices and are fallible.
In other words, she might have been bitten by some problem in the past which was solved by writing it like this - ask her about it, you might learn something.
Or, she perhaps thinks it's better, and can't articulate a strong benefit over personal preference; or that was the way she learnt, and hasn't seen a strong need to change - you learn something from that, insofar as there is more than one way to articulate the same semantics.
(I have a strong preference for != because it's neater - fewer parentheses; and why would the language designers bother providing != if you weren't intended to use it - but these are my personal preferences).
Or, she maybe meant to use !=, and forgot to go back to fix it. It's easy to forget to clean things up.
In Java, there is no difference between a!=b and !(a==b). Choosing the later form is a stylistic choice, which, to be honest, most static analysis tools/IDEs will issue a warning about.
Your teacher is using other ways to write the if-statement.
It doesn't matter if you write
if(array[i] != null)
or
if(!(array[i] == null))
because ! defines as not in most programming language. In this situation both of them are equal.
In conclusion, you can choose whatever style you like.
Hope you understood and good luck!
Always ask your teacher when you wonder about something :)
The other answers are correct. For your example there is no difference - chose what you like the most. But I'd like to give some more reasons to chose one way over the others.
My advice would be not to go for if (! (...)) in general because:
Most people wouldn't do it like this. You will have to read and understand code written by others and others will have to read and understand your code. Quirks like that greatly reduce the redability and collegues will frown upon you.
Some projects might follow a coding standard that doesn't allow this.
Think about the execution. For more complex statements the different style might have an impact. Think of !(A || B || C || D) vs !A && !B && !C && !D. It might happen that in the former A-D have to be evaluated and then the resulting boolean is flipped wheras in the latter it might be enough to see that !A evaluates to false and you can already stop there (because any conjunction with a false member will be false).
But also think about readability again. Actually it might be easier to grasp writing NOT(is_a_digit OR is_a_letter OR is_a_dot) instead of
NOT(is_a_digit) AND NOT(is_a_letter) AND NOT(is_a_dot).
That being said, it's also good to know about Yoda-style writing which is kinda related. Imagine you have String someString; that might contain a string or might be null. Now imagine you'd like to check if its equal to "some specific string": someString.equals("some specific string") - yikes, this might produce a NPE because when someString is null there is no method equals to call on it. Instead you'd have to do someString != null && someString.equals("...") or the Yoda-way of "some specific string".equals(someString). There's also other helpers like Objects.equals().
Sometimes extra parenthesis can make things easier to grasp and sometimes they don't.
While I don't agree that "there are no stupid question" I'd say that sometimes it's better to ask a dumb question than falling behind in the lessons because something nags at you or you missed some important bit. In this case I'd consider this a good question (unless she just told you why).
There is a difference between a!=b and !(a==b), it depends on personal preference and what code you're using. In python a!=b is faster, as other answers have stated.
Actually there is no difference between if (!(array[i] == null) and ìf (array[i] != null)
In this case we can imagine a scenario. Lets say array[i] is not null, then for the first expression inside if(!(false)) , eventually !(false) will be true.
And for the second expression the return result will be directly true.
So seconnd expression is recommended always.
The former is not a good idea in some languages like python,
In python, for former the better way is
if not something==somethingElse
although for latter its perfect, if something != somethingElse,
So learning the former might get you in some situations where the bug is so subtle that debugging gets really hard, especially when you use this condition in while loop
!= is more efficient than !(). I ran a test in python, and it speaks for itself.
(not a and not b and not c and not d) 10.07692837715149
(not (a and b and c and d)) 11.208963394165039

Why can we call .orElse() on Optional.of()?

I'm curious why is it possible to do this (at least on Java 8):
Optional.of(null).orElse("something");
Optional.of(null) is basically a guaranteed null pointer. Making possible to invoke .orElse() on it gives a clumsy developer unexpected holes to fall into. I've been looking around to see if there's any justification to this. Maybe there's some scenario that this is supposed to address?
You can do this for the same reason you can write ((String) null).length(). The Java compiler has a static checker for certain things like type-safety, but does not check for or reject code which provably throws a NullPointerException. If it did, the code throw new NullPointerException(); would not be allowed either.
It's not generally the case that code which throws an exception is a mistake. While a static checker could detect this kind of thing and warn about it, it would be bad if this was an error. Some IDEs will generate their own warnings about probable-mistakes, but you have to decide what is or isn't worth checking for.
Detecting this probable-mistake requires a static checker designed with knowledge of the behaviour of the Optional.of method. The authors of the Java Language Specification have made the decision to warn for things like unsafe casts, but not for anything which depends on the semantics of the methods being used. One advantage of this decision is that it means the JLS can be maintained separately from the Java Class Library documentation.
There are languages where there is support for null checking right into the compiler (or even better languages that don't have such a "thing" at all) - this is burned into the compiler.
javac is not a such compiler and the be frank - I don't want it to become like this either. There are languages where there is syntax like ! or ? or !? - when I read this code it either screams on me or asks me something (this is my opinion).
Now, recall that Optional is designed for return types, so inside your method body you use an Optional chain of methods. If you really want to check if something is null or not there is Objects::requireNonNull - use that; if you are unsure if something is null or not, you could use Optional::ofNullable.
I know and read the arguments for Optional::of and Optional::ofNullable, I still don't like it, I wish it could be just the latter. But hey, people don't have to agree all the time: we do have Optional::isEmpty and Optional::isPresent. Is that a good decision? I don't know.
Like any other method call, you can pass null to any object reference, Optional is no different. Could they add semantics for the javac to support only Optional::of and null checking? Probably. How many people would request such a support for and this feature please?
Optional.of(null).orElse();
Obviously the above code will always cause an exception. But what about:
Optional.of(someMethod()).orElse();
with
Object someMethod() { return null; }
You probably think: sure, same thing.
Well, actually that is wrong. What if a subclass overrides someMethod() to return a value other than null?! Thus you can't decide at compile time whether that method will always return null at runtime.
Long story short: there are plenty of obvious, and also less obvious situations where the compiler could apply all kinds of techniques, like data flow analysis to determine whether code will result in a runtime exception or not. But there are also many others where that isn't possible.
The point here: it is up to the people defining the language to determine what they expect compilers to care about.
The java people opted for a simple compiler. One that compiles fast, and that isn't overly complicated to implement. Why? Because the compiler simply avoid overly complicated checking.

Is there a real reason to use Optional.of()?

I've read here why Optional.of() should be used over Optional.ofNullable(), but the answer didn't satisfy me at all, so I ask slightly different:
If you are SURE that your method does not return null, why should you use Optional at all? As far as I know, the more or less only purpose of it is to remind the "user of a method", that he might have to deal with null-values. If he does not have to deal with null-values, why should he be bothered with an Optional?
I ask, because I recently made my service-layer return Optionals instead of nulls (in certain situations). I used Optional.of() and was highly confused when it threw a NullPointer.
A sample of what I did:
Optional valueFromDB = getUserById("12");
User user = valueFromDB.get();
.....
public Optional<User> getUserById(String id) {
//...
return Optional.of(userRepository.findOne(id)); // NullPointerException!
}
If null is not possible, I don't see why one would wrap it in an Optional. The dude in the linked answer said "well, if a NullPointer happens, it happens right away!" But do I really want that? If the sole purpose of an Optional is, to remind the programmer who gets such an object, to keep null in mind (he HAS to unwrap it), why should I want to have NullPointerException at wrapping-time?
Edit: I needed to edit the question, because it got marked as duplicate, even though I already linked said question from the start. I also did explain, why the answer did not satisfy me, but now I need to edit my text with an explanation.
But here is some appendix to what I want to ask, since I got 5 answers and everyone answers a different case, but none fully covered what I try to ask here:
Is there a reason, that Optional.of(null) is impossible and they specifically added Optional.ofNullable() for the null case?
Using streams should not be the problem with my idea of the implementation.
I got a lot of insight from your answers, thanks for that. But the real question has not been answered until now, as far as I can tell/read/understand.
Maybe I should have asked: "What if we remove the Optional.of() method and only allow Optional.ofNullable() in Java 9, would there be any problem except backwards-compatibility?"
You are mixing up the API design rationale with knowledge within a particular implementation code. It’s perfectly possible that a method declares to return an Optional, because the value might be absent, while at a certain code location within the method, it is known to be definitely present. I.e.
String content;
public Optional<String> firstMatch(String pattern) {
Matcher m = Pattern.compile(pattern).matcher(content);
return m.find()? Optional.of(m.group()): Optional.empty();
}
This method’s return type denotes a String that might be absent, while at the code locations creating an Optional instance, it is known whether the value is present or absent. It’s not about detecting a null value here.
Likewise, within the Stream API methods findFirst() and findAny(), it will be known at one point, whether there is a matching element, whereas supporting the conversion of its presence to absence in case of a matching null element is explicitly unsupported and supposed to raise a NullPointerException, per specification. Therefore, Optional.of will be used to return the matching element, which you can easily recognize in the stack trace when using Stream.of((Object)null) .findAny();
The other reason to use Optional.of(value) when you know that value can't be null is that if you want to do additional filtering operations on that Optional.
For example:
public static long getPageSizeFrom(HttpServletRequest request) {
return Optional.of(request.getParameter("pageSize"))
.filter(StringUtils::isNumeric)
.map(Long::valueOf)
.filter(page::hasPageSize)
.orElse(page::getDefaultPageSize)
}
I think you are right with your opinion that you should not use Optional if you are sure that you always have a return-value.
But your method is not sure, that it always returns a value!
Think of an call to getUserById(-1). There is (normally) no User with this id, and your userRepository will return null.
So in this case you should use Optional.ofNullable.
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#ofNullable-T-
Optional is one of those things that has been imported from functional programming languages and dumped into the laps of OO and procedural programmers without much background explanation...which has caused much pain and hand wringing.
First, a quick link to a blog post (not by me) which greatly helps to clear the air on this: The Design of Optional
Optional is related to functional programming types like Haskell Maybe. Because of the way strong typing works in functional programming, a programmer in that language would use Maybe to say that a value can be either Something, or Nothing. The Something and Nothing are actually different types, here. Anything that needs the values inside a Maybe has to handle both - the code simply won't compile if it doesn't handle both.
Compare that scenario to what is the typical situation in C-based object-oriented languages (Java, C#, C++, etc.) where an object can either have a value, or be null. If a method needs to handle null parameters as an edge case, you need to explicitly write that code - and being the lazy programmers we all are, it's just as often we don't bother to.
Imagine what coding would be like if code wouldn't compile unless null cases were always explicitly handled. That's a pretty close comparison to what happens when using Maybe in functional languages.
When we pull language features over from functional programming, and the compiler behaves the way it always has, and we code the way we always have... you can see there's a disconnect happening.
Separately, Optional can be used as a simple stand-in for null. Because it seems familiar that way, and is new, magpie developers are prone to using it as a replacement for situations where null-checks would have happened before. But, in the end, is foo.isPresent() really so different than foo != null. If that is the sole difference, it's pointless.
And let's not even get started on how Optional can be a stand-in for autoboxing and unboxing in Java.
Now, getting back to your specific question about the particular API of Optional in Java, comparing ofNullable() vs. of(), the best I can work out is that you probably aren't expected to use those in typical code. They are mainly used at the terminal end of stream() operations. You can look at the code to Optional.of() vs. Optional.ofNullable() and see for yourself that the only difference is that ofNullable checks if the value is null and arranges things for that situation.
My jaded eye doesn't see a whole lot of benefit to using Optional in Java, unless I am using Java 8 streams and I have to. Some would say that the main benefit of using Optional as a type for non-stream usage is to specify that a particular parameter is optional - that is, the logic takes a different route if it's there vs. not there. Which, again, you can simply do with null. But I would say that the mental baggage associated with Optional means that for every forward step of supposedly more verbose code, you are taking multiple steps backwards with requiring people to understand that the Optional (in this specific case) is almost entirely cosmetic. For the situation you described, I would probably go back to using nulls and null checks.
Angelika Langer says that Optional.ofNullable is only a convenience-method, calling the other both static methods from Optional. It is implemented as:
return value == null ? empty() : of(value) ;
Also she says that Optional.ofNullable was added lately to the API.
Here is her text in german language: http://www.angelikalanger.com/Articles/EffectiveJava/80.Java8.Optional-Result/80.Java8.Optional-Result.html
So I would use Optional.of only when null is an error, which should be found early. This is what Tagir Valeev said in:
Why use Optional.of over Optional.ofNullable?
The practical answer is: on most occasions, no. As you mention, if the whole point of using Optional is not knowing if a value can return null, and you want to make it explicit in certain API, the fact that .of() can throw a null exception does not make any sense. I always use ofNullable.
The only situation I can think of is if you have a method that returns Optional (to make explicit this null-value possibility), and that method has a default/fallback value under some circumstances, you will return a "default value" Optional, using .of().
public Optional<String> getSomeNullableValue() {
if (defaultSituationApplies()) { return Optional.of("default value"); }
else {
String value = tryToGetValueFromNetworkOrNull();
return Optional.ofNullable(value);
}
}
Then again, someone can question whether in that case you can return this default value in case of a null.
Metaphysical discussions aside, IMHO if you use Optionals, and want them to make any sense and not throw exceptions, use ofNullable().
I agree that Optional.of is counterintuitive and for most use cases you would want to use Optional.ofNullable, but there are various purposes for Optional.of:
To explicitly throw a NullPointerException if the value is null. In this case Optional.of functions as a Guard.
When the value simply cannot be null. For instance, constants like Optional.of("Hello world"!). This is a programming esthetics thing. Optional.ofNullable("Hello world!") looks weird.
To turn a non-null value into an Optional for further chaining with map or filter. This is more a programming convenience thing. Just like Optional.stream() exists to turn an Optional into a Stream for further chaining.
"What if we remove the Optional.of() method and only allow Optional.ofNullable() in Java 9, would there be any problem except backwards-compatibility?"
Yes, of course there will be compatibility issues. There's just too much code out there using Optional.of.
I agree with your general sentiment though: Optional.of is doing too much (wrapping the value and null-checking). For null-checks we already have Objects.requireNonNull which is conveniently overloaded to accept a descriptive text.
Optional.of and Optional.ofNullable should have been discarded in favor of a constructor made available for users:
return new Optional<>(value);
For null-checks this would have sufficed:
return new Optional<>(Objects.requireNonNull(value, "cannot be null!"));

What is the preferred way to write boolean expressions in Java

I have always written my boolean expressions like this:
if (!isValid) {
// code
}
But my new employer insists on the following style:
if (false == isValid) {
// code
}
Is one style preferred, or standard?
I prefer the first style because it is more natural for me to read. It's very unusual to see the second style.
One reason why some people might prefer the second over another alternative:
if (isValid == false) { ... }
is that with the latter you accidentally write a single = instead of == then you are assigning to isValid instead of testing it but with the constant first you will get a compile error.
But with your first suggestion this issue isn't even a problem, so this is another reason to prefer the first.
Absolutely the first. The second betrays a lack of understanding of the nature of expressions and values, and as part of the coding standard, it implies that the employer expects to hire very incompetent programmers - not a good omen.
Everybody recognizes this snippet:
if (isValid.toString().lenght() > 4) {
//code
}
I think your second example looks at the same direction.
It was discussed for C# several hours ago.
The false == isValid construct is a leftover from C-world, where compiler would allow you to do assignments in if statement. I believe Java compilers will warn you in such case.
Overall, second option is too verbose.
IMO the first one is much more readable while the second one more verbose.
I would surely go for the 1st one
You are evaluating the variable, not false so the latter is not correct from a readability perspective. So I would personally stick with the first option.
I'm going to attempt a comprehensive answer here that incorporates all the above answers.
The first style is definitely to be preferred for the following reasons:
it's shorter
it is more readable, and hence easier to understand
it is more widely used, which means that readers will recognize the pattern more quickly
"false==..." rather than "...==false" is yet another violation of natural order,which makes the reader think "is there something strange going on that I need to pay attention to", when there isn't.
The only exception to this is when the variable is a Boolean rather than a boolean. In that case the second is a different expression from the first, evaluating to false when isValid is null as well as when it is Boolean.FALSE. If this is the case there are good arguments for using the second.
The second style doesn't require you to negate the expression yourself (which might be far more complicated than just "isValid"). But writing "isValid == false" may lead to an unintended assignment if you forget to type two ='s, hence the idiom is to put on the right side what can't be an rvalue.
The first style seems to be preferred among people who know what they're doing.
I just want to say I learned C twenty years ago in school and have moving onto Perl and Java and now C# which all have the same syntax and...
I think (!myvar) is the most popular
I think (myvar==false) is just fine too
in 20 years i have NEVER EVEN SEEN
(false==myvar)
I think your boss is smoking something-- I'm sorry but I'd take this as a sign your boss is some kind of control freak or numbskull.

Is defining a "ProbableBugException" code smell, paranoia or good practice?

In my Java code, I occasionally run into situations where I have to catch a checked exception from a library function that I'm pretty sure can't occur in my use case.
Also, when coding, I sometimes notice that I'm relying on certain inputs from other modules (my own) to have or not have particular features. For example, I might expect a string to be in a certain format etc. In these situations, I would often put in a verification step, although I control the code that send the input myself.
At the moment, I'm working on a quite complex product that I want to be very reliable. Among other things, I want it to collect information from caught exceptions and automatically file bug reports. For the above two scenarios, I therefore defined an (unchecked) "ProbableBugException", that tells me I made a mistake in the code delivering the input data.
Is that a) stupid, b) paranoid or c) good practice? This is going to be subjective, I'll put up three wiki answers so we can vote away without rep warping.
ETA:
Thanks to Svend for pointing out that Java has assertions, I didn't realize that. Assertions are actuall pretty much what my question was about, but I only knew them from C and have never used them there.
I'm thinking that using an assert is what you really want there ("probably bug").
It's stupid, because:
the exception should be much more specific, like InvalidInputException
you should think harder about the input side, it's likely that it's shaky if you feel you need that kind of exception
It's good practice, because:
you might have a coworker coding on the input side and the two of you might have misunderstood each other
if you make a mistake, fixing it becomes trivial
in situations where the input side is a plugin of some sort, it helps the plugin developers (who might be external) to deliver correct input.
I always expect the unexecpected.
I often have code like this : ( $div will never be 0 into my code )
if( $div != 0 ) {
$var = $var2 / $div;
} else {
/*
* It should never happen
*/
throw Exception( 'relevant message' );
}
I always protect myself from me and the others

Categories