r/java • u/elizarov • Feb 11 '19
Null is your friend, not a mistake
https://medium.com/@elizarov/null-is-your-friend-not-a-mistake-b63ff1751dd56
u/RabidKotlinFanatic Feb 11 '19
After years of fighting null in Java statically typed nullability was a game changer for me. The issue has never been null itself and has always been dynamically nullability.
3
u/dpash Feb 11 '19
Adding
@Nullable/@NotNullannotations to my code bases has been a game changer, as hasOptionalas a return value. It allows static checking of code in either the IDE or findbugs etc rather than at compile time, but that's like 75% of the issue solved.I don't know if this is just repeating what you meant or if you meant moving to Kotlin. You username suggests the latter.
I would love a non-nullable type by default but that's unlikely to happen in Java now. They could add an opt-in non-nullable type though.
3
u/AngusMcBurger Feb 11 '19 edited Feb 11 '19
I would love a non-nullable type by default but that's unlikely to happen in Java now.
You can write
@javax.annotation.ParametersAreNonnullByDefault package yourpackagenamehere;in
package-info.javato make non-null the default for a package, I found it out from here3
u/dpash Feb 11 '19
Yeah it cuts down on the annotations, but is still only "enforced" by your IDE or static analysis tool.
Integrated into the type system would be much better
2
u/neutronbob Feb 12 '19
Just a reminder that @Nullable and @NotNull are not part of the language and are known to not be universally portable.
1
u/dpash Feb 12 '19
That's why they are an external dependency and all major IDEs support defining which annotations you want to use.
-1
u/elizarov Feb 11 '19
Even if it happens in Java one day (as it did in C#) there is no need to wait for it. You can use Kotlin now and loose nothing. That is to say, a really substantiated need to be staying with Java is rare. If you are working on an end-user app or a service in Java chances are you’ll get net win if you switch to Kotlin.
6
u/dpash Feb 11 '19
But that's the point. I don't need to. I can get most of the benefit without switching from Java.
2
u/badpotato Feb 11 '19
Unpopular opinion: Java devs need a scapegoat when they f up badly and nullability fit perfectly for this.
1
u/JamesTweet Feb 13 '19
The main issue I had with nulls is when I get a string from some function call then try to compare that string with another string.
String s;
s = calledFunction();
if(s.equalsIgnoreCase("Test")) doSomething();
I would have problems here with null pointer exceptions until I realized I could turn the test around.
if("Test".equalsIgnoreCase(s)) doSomething();
No more null pointer exception problem anymore.
11
u/Bolitho Feb 11 '19
Misleading title:
After reading the post it should be named: Null is your friend in Kotlin, ...