170 points · by mikece · 4y ago · 225 comments
This is perfectly legal code, where the optional wrapper itself is null:
Optional<String> getMiddleName() {
return null;
}Optional isn't half-assed because it was never envisioned as a general solution to the null problem. It's simply an interface that's useful in streams and other similar cases for method return values, and it does the job it was intended to do reasonably well. It's possible that a solution to nulls in the type system could have obviated the need for Optional, but I don't think that delaying lambdas and streams until such a solution was found would have been a better decision.
First, because exactly the type of code that the parent commenter showed. I've actually seen this in production code (and shrieked). The fact is that without language-level support, you can end up getting the worst of all worlds.
Second, like all things in Java along the lines of "why use 1 character when 10 will do?", the Optional syntax is verbose and annoying to use.
But, most importantly, the fundamental issue is that all classes are optional by default in Java (indeed, that's the problem at hand). Adding an Optional class doesn't really mean you can make any non-nullability assumptions about other classes, especially when using different libraries. The Optional class just added more complexity while simplifying very little.
When pron mentioned "this is actively being worked on", he meant exactly this problem. [1] [2] Java is currently working on changing the dynamics of the language such that classes can in fact be non-nullable. Last I checked in, this was the notion of `primitive` types being added in project Valhalla.
Optional just so happens to be one of the types in the JDK that will converted over to being a `primitive` type.
Now, what that means in terms of existing code I believe what's being discussed. How do you handle
public Optional<Foo> bar() { return null; }
?We'll see, it might be something like changing the code to something like this
public Optional<Foo>.val bar() { return Optional.empty(); }
which would guarantee that the optional type returned is in fact never null.[1] https://github.com/openjdk/valhalla-docs/blob/main/site/desi...
[2] https://github.com/openjdk/valhalla-docs/blob/main/site/earl...
I'm sorry, but I don't think you understand the purpose that "Optional" was intended to serve. And are unduly dismissive simply because it does not serve some larger purpose that was not intended.
Perhaps it's just me, but I don't equate optional with nullable. An optional value is just the designer specifying that you may or many not specify that value, while nullable are objects which may or may not have been initialized yet.
Even though nullables have been used and abused to represent optional values, I'm not sure it's a good idea to conflate both. It would be like in C++ equating shared pointers with optional types.
Yeah technically tomorrow morning Java could fix it, but there have been kingdoms built on the current situation. C# took its lumps years back on breaking things and so there were fewer kingdoms to demolish. And if you fix it, it'll be years before it trickles down to a large portion of devs who don't get to work at the bleeding edge, or even near the edge.
But in this case, I don't see what additional kingdoms there would be to demolish. No Java code employs nullability types now just as it didn't in 2014. Optional does the limited job it needs to do rather well, and will become even better when we extend pattern matching, so there would be no need to demolish it even if and when we have some solution to nulls. As you can see here (https://docs.oracle.com/en/java/javase/19/docs/api/java.base...) it's used sparingly and in specific situations, definitely not as a general null replacement.
Regardless of the intent, once it got into the hands of enterprisey java devs, it immediately got used in two ways:
Tri-value nulls: treating null, None and Some in different ways.
Annotation hell: spam nullabilty annotations like @Nonnull Optional haphazardly everywhere with no semblance of soundness in sight.
When actually used as intended (by the 90 percentile coders on the team), it just bludgeons the GC to death because the JIT does not always do the right thing and elide the extra heap indirections.
They’re almost as bad an idea as type erasure!
What's to investigate? Just copy what C# did and be done with it.
Thanks, I'd rather wait.
There's nothing inherently wrong with an "absence of value, value"
Optional.empty is not null, it's no-value
In our code base this means we have a the rule that Optional is only allowed for returns so we aren't adding 3rd cases all over the place.
Either it's null, so has no value, or it's not null so has a value, and you can check for null-ness. What more is needed?
Seems like the opposite, a guaranteed non-null value at core language level, would be novel instead...
It's really an eye-opener when you compare kotlin and scala, with all their superficial similarities: Where kotlin simply takes the @Nonnull annotation, promotes it to a core language feature and drowns it in convenient function-scope syntactic sugar until it's actually nice to use, scala opts for Option and stacks layer upon layer of architecture trying to make Option somehow disappear. I lost half a decade holding on to plain java snobbishly dismissing kotlin as a second class scala before I finally got converted.
Defaulting to not-nullable is a great idea. Much less boilerplate.
Personally I use notNull(..) over @NonNull since it actually fires when you expect it to (as opposed to whether your framework dispatcher interceptor trigger decided to invoke it)
They couldn't have fixed it while retaining backward compatibility.
Opt-ins exist. That's what .net ended up doing: by default the language uses "ubiquitous" nullability, but you can enable reference nullability support at the project or file level.
If you do that, references become non-nullable, and have to be explicitly marked as nullable when applicable.
void foo1(Bar bar)
{
...
}
void foo2(Bar? bar)
{
if (bar != null)
foo1(bar);
}
Which wouldn't compile if you didn't have the `if` condition.Also because std::optional does essentially the opposite. It’s a more efficient _ptr rather than a safer one. Optional<T> is strictly less efficient as it implies an additional allocation.
Thanks for the explanation. Wow, this sounds like a a bit of a mess, one because of the allocation, and also because it seems there are multiple ways something can be semantically null.
In my experience, Scala does pretty well without it.
I guess is your point that the language should make it impossible to write bad code, not just make it easy to write good code?
Optional are quite nice and we use it where appropriate, they play nice with streams which is a nice bonus.
@NonNull
Optional<@NonNull String> getMiddleName() {
return null; // error
}At the same time, we have adopted Kotlin as well. Interestingly, most of our developers prefer to stay on Java... not because they love Java, but because of familiarity and that they seem to think it's "good enough".
Anyway, we haven't had a large rate of NPEs for a very long time and when one actually happens in the wild we're extremely surprised!
That said: looking forward to the specification[1] that's being cooked up as Java absolutely should have had this a long time ago (as mentioned in the post).
I have been using Kotlin on Android for a few years now, and really enjoy the extra expressiveness and conciseness that the language offers ... but have come to the conclusion its much easier to write unreadable kotlin code than java code.
One of the things I think makes Kotlin hard to read is scoping functions (apply/also/let/run/with). Based on their names alone, the newcomer can't tell what they do (I had to consult a table for weeks on whether they returned the original object, last expression, and whether they passed it, this, etc).
I do love these when used at the right place, right time, and "just enough" but I keep coming into contact with code that nests these 4-5 levels deep:
aaa?.run {
bbb?.run run2@ {
ccc?.run {
ddd?.run {
this@run2.foo()
// whats in scope here urgh
}
}
}
}
Other pathologies I see are making any method (foo), that operates on X, as an extension method X?.foo(). Then the namespace for X gets polluted with all these things.One of the great things about Kotlin's nullability in the type system is the operators like ?. and ?: ... but often see code like this:
aaa?.bbb?.ccc?.ddd()
Is it safe, yes, yes it is. It won't crash, but what happens if one of these is null, and should not be? There is nothing in Kotlin forcing people to write this way, but find Java's explicit checking of null made people think more of the "negative case" (throw an exception? etc)Like anything else, I guess we could use linting rules, it comes to having good taste ... which is not in abundance.
What worries me the most though, is that in the beginning, Kotlin was mostly additive on Java. I read, in biological systems, adding is easier that changing or removing. It seemed like Effective Java + Typed Groovy. Now as Java has "last mover" advantage, and adopts the good parts of Kotlin, I am worried its not just additive, they need interop between different implementations (records vs data classes).
If you need all aaa through ddd to be non-null you return early or you check ahead of time
aaa ?: return
bbb ?: return
ccc ?: return
ddd ?: return
or if (aaa != null && [the rest] != null) foo(aaa, bbb, ccc, ddd)
Since if foo needs them all to be not null they should be passed in aaa?.bbb?.let{ bbb -> //definitely should not be null in this case
bbb.ccc?.ddd()
} ?: return // or throw an exception val aaa = aaa ?: return
val bbb = bbb ?: return
val ccc = ccc ?: return
val ddd = ddd ?: return
if those three-letter friends happen to be "getter vals" that might change behind your back (the compiler is perfectly aware of the difference).That's the one gripe I have with kotlin, those "getter vals" that aren't even remotely related to immutability. Likely a consequence of building closely on top of java, there's simply no way an interface could promise to never return two different references from a call on the same object without that promise being a lie. And as usual, kotlin provides gentle damage mitigation on syntax level: "val x = x", as in the four lines above.
I would have preferred something even more consise like "val=x" though, where the name overlay is promoted to explicit intention by not typing it twice, as in "call that getter and nail its return to the getter's name for the remainder of our scope". People tend to be reluctant with that name hiding, unsure of it's good style or bad, if there was an explicit shortcut it would be blessed as The Kotlin Way (and, as you said, it's so much better than getting pulled into that let/also nesting abyss that feels clever while writing but turns on you before you are even done)
I mean I love Kotlin, but as you mention there is just so much syntax. The simplest things can be done 100 different ways and it's hard to say what's idiomatic.
I'm personally going to be ruthless about "syntax simplicity" in code reviews. Otherwise I'm imagining a situation where the dream of shared code really just becomes "Android devs throwing a black-box library over the wall at iOS devs" because only they spend enough time with Kotlin to understand it
In Virgil, a method on an object (or ADT) can declare its return type as "this". Then the method implicitly returns the receiver object. That trick is very useful to allow a chain of calls such as object.foo().bar().baz(). I find it readable and easy to explain:
https://github.com/titzer/virgil/blob/master/doc/tutorial/Re...
C# has made it possible to gradually roll out stricter nullability checking as well. The static analysis gets integrated into the regular language analyzers. Incremental migration is the only way to go.
It was a lot of work to get there and we're still not totally there yet. Dart still supports running legacy code that isn't null safe. But I'm really glad we did this and very grateful that Leaf and others on the team were able to design a null safety type system that:
* Defaults to non-nullable.
* Is fully sound.
The latter in particular is very nice because it means the compiler can take advantage of null safety to generate more efficient code, which isn't true in languages like Java, C#, and TypeScript where their null safety type rules deliberately have holes.
You technically can do "= null!", which means assign null by default, but assume it is not null. This is currently the recommended way to do deserialization, where you know the value is not null, but you have not explicitly filled it.
I feel C#'s nullable has helped me personally to avoid a lot of potential bugs and also changed the way I write code in a lot of places - like creating `bool Try...(..., out var)` style APIs instead of "old school" returns-null/throws style stuff, which I think make a lot of code cleaner and more easy to read.
Sometimes nullable can get a little messy and annoying, especially when retrofitting old code to make use of it without breaking existing APIs, and all in all the way C# does it is a clear net win in my opinion.
Lets not forget the whole drama with prefix ! planned for .NET 7.
I can only look on with disappointment when new (or newish) languages include null as part of the language instead of doing something more sensible like having an Option/Either type. Of course, I won't name names... cough Go cough
Java's biggest failure in null handling was allowing EVERY reference type to be null without a way of specifying that it could be non-null. This basically ensured that null could creep in almost anywhere.
Allowing a type to be null should always be opt-in. It still bothers me that I have to put NOT NULL in almost every SQL column definition because the SQL spec has columns default to being nullable. Ugh. At least SQL does allow me to choose nullable vs non-nullable, unlike Java.
It’s even excusable for C# in the early aughts.
There are roundabout hacky ways like parsing the JSON into a map[string]any to check if it’s there, but it’s so ugly and requires so many lines of code.
Makes the
// Java
name = personService.getPerson(123).getName()
problem less likely since you'd generally have to write: // Go
person, err := personService.GetPerson(123)
if err != nil { ... }
name, err := person.Name()
if err != nil { ... }
Definitely more verbose than maybe // TypeScript
personService.getPerson(123)?.getName()
but I think that's part of Go's tradeoffs -- much more likely that errors will be annotated more correctly (i.e., in Go you'd be more likely return an error like "failed to load person: 123" if it was the GetPerson call that failed rather than a generic error that doesn't describe which step failed)The story I like to tell about how people abuse Java is this:
@nullable Optional<Boolean>
I don't know if this is still the case but you could literally find many instances of that in Google3 (and not all of them were the product of an auto-generated tool). I mean it's a super-large code base. There was a cleanup at one point for the (many) instances of 1204 in the code base.The way I like to describe this is "for when 3 values for your boolean just aren't enough" (since you obviously now have 4 states: 1) null 2) Not set 3) Set, true 4) Set, false).
I have a few rules that have held up v ery well over the years including:
1. If you don't do arithmetic on it and it's not an ID of some kind, it's almost certainly not a number (eg people who store SSNs as INT fields); and
2. It's almost never a boolean. You're almost always better off replacing any boolean with an enum. Not only is this typesafe but if done right adding an enum value will cause compiler errors because you've been exhausitve with switches without a default case.
What I haven't tried is "migrate on touch" with a strict rule that there must be explicit commits just before and after the conversion (plus a third commit documenting the file rename separately, before or after). That could perhaps work out well - or not help much at all, I don't feel like I could even guess.
But other than that, the intermediate state of partial conversion is surprisingly acceptable to work with, I'm not disagreeing!
Migrating millions of lines of code is a non trivial effort. They'll be stuck with bits of Java for quite some time. So, this helps make that less painful.
Or you throw all the null safety away and write unsafe java code but in Kotlin the same as the Java code you're working with.
Ah, "acclimation" -- thought at first you were saying that Java devs love it for a few weeks and then hate it lol.
Most of the changes for me from 10/20+ hours to now we're more about identifying a style that works as effectively as I can. These types of behaviours are normal in all but the most idiomatic languages, so if anyone is doing java dev as their daily language, Kotlin felt very natural(though you really are limited to Intellij since the IDE does a ton of lifting to make your life easy).
Kotlin is probably more similar to Java than any other mainstream language. There’s almost no learning curve there, while going from Java to other “easy” languages like Python requires significantly more time to get used to.
I either have code that can't be null (e.g. getters of lists that create a list if the field is null, outright validation before usage), code where null has a desired meaning that must be handled (new JPA entity with no key yet) or code where the Nullpointer will lead to a client/user/implementor caused bad request style response.
What the hell are you guys doing for you to spend significant amounts of time on NullpointerExceptions?
On the same note, I didn't understand the inclusion of Optional in Java. Always felt like some annoying special flavor type of custom Java nuisace like vavr or jooq.
1) Reversing string comparisons:
"literal".equals(variable)
instead of variable.equals("literal")
2) Always initializing lists instead of leaving them to default to null public class SomeClass{
private List someList=new ArrayList(); //or Collections.emptyList()
...
}
The problems with NullPointerExceptions can mostly be solved by teaching programmers to use these strategies and teaching them to look for boundaries where nulls can slip in.The real problem happens when things get scaled up. If you have thousands of developers then it makes sense to take steps to automate the problem away. Also, if the code is used by billions of users then even rare NullPointerExceptions will happen frequently. So it makes perfect sense for Facebook to be the one to work on this.
Everyone should know these things by now. They are good things to ask about in interviews.
The slow-down occurs from all the extra thinking that happens once [your teammate] allows nulls into the code "as a feature".
If you assume no nulls, then you get to lean on the type system. A String is actually a String, not an instruction to GOTO the nearest enclosing RuntimeException handler.
And honestly, I'd be mostly happy to work on the no-null assumption, hit a few NPEs, and fix them as I go. But someone else will decide that nulls are OK as values, and now every value is suspect. Which means you can no longer just blindly assert against nulls.
And that's the value-add of Optional. You can use it to deliberately represent things that aren't there, meaning you can go back to treating every null as a bug to squish, rather than a design choice.
I don't understand the fuss either. Logic problems from improper error handling is way worse than NPE.
Edit: Pointers that can be null actually are a sum type but without the fancy pants hype.
It interacts nicely with stream pipelines.
Obviously there are a lot of lazy/bad developers and the larger the company/team the more likely you have some of them. The irony is when this comes up in discussions about places like Google and Facebook that have built up a cult of believing they are better than everyone else while seemingly having lots of trouble dealing with these kinds of issues.
I don't hate Optional, but what I find is the same people who can't handle using null also fall into the Optional anti-patterns.
If I were still writing Java I would throw in some exception throw/catching based Haskell style do notation for binding nullables, i.e.
var nullableResult = nullable(() -> {
var a = bind(getNullableA());
var b = bind(getNullableB());
doSomethingRequiringBothNotBeingNull(a,b);
});
In my experience, Java developers don't want null safety though (the ones that do switched to Kotlin anyway).If you have getAccount().getContact().getPhoneNumber() and contact is null, you'll get an NPE. The question shouldn't be: "How do I shove the NPE under the rug for the next 1337 coder to deal with?", the question should be: "How did I initialize an Account without a Contact?"
Static analysis (detecting) is the opposite of "covering up".
> "How did I initialize an Account without a Contact?"
As long as your language lets you do it, your teammates will do it. And in many cases it won't be accidental either. Your teammate will want an Account with its Contact set to null.
Every time I see people "deal" with this problem, it looks like this:
if (getAccount() != null &&
getAccount().getContact() != null &&
getAccount().getContact.getPhoneNumber() != null) {
// do something
}
// don't put an else condition in, just keep going and let the program
// produce the wrong result in a confusing way when it happens in production
I actually blame rampant code generation and an adamant refusal to even consider object-oriented design for this problem - this sort of case ought to be handled by something like: getAccount().callContact()
(or whatever you were going to do with the phone number when you got it). Insistence on generating code from SQL schemas or XML DTDs and then writing procedural code makes that pretty much impossible, though.C# at least has null propagation and pattern matching that can make that line:
if (getAccount()?.getContact()?.getPhoneNumber() is string pn) {
// do something with `pn`
}
The "idiomatic" C# way would also include properties: if (GetAccount()?.Contact?.PhoneNumber is string pn) {
// do something with `pn`
}Class based OOD is way harder than that. There's a reason codebases are full of these train wrecks (the unofficial official name of the pattern). And it's not because of auto generation and/or laziness. It's because, despite what's on the tin, passable - nevermind good - OOD doesn't look anything like how we actually think of objects as humans.
``` if (account == null) { throw NoAccountException }
if (account.contact == null) { throw AccountWithoutContactException }
if (account.contact.phoneNumber == null) { throw ContactWithoutPhoneNumberException }
// do stuff here ```
Well yeah that's exactly what static analysis can tell you - what code path led to that.
You're saying this project should be what it already is.
Actually I already know - he got it from a JSON feed from an external system and ran that JSON through an automated code generator.
I've brought it up when using Swift and Kotlin and it takes so much energy for people to realize that safety operators, which feel really really good to use, accidentally sweep up major issues
People assume you're missing something when you explain that they need to get more comfortable with force unwrapping (which is intentionally introducing a NPE)
-
But for example, if you have getAccount().getContract().getPhoneNumber() so you can show it in a settings page, you should not throw an NPE. You can easily correct the issue in a non-invariant breaking way by say defaulting to "<missing>" in the UI.
But if you have getAccount().getContract().setSomeFieldWithRealWorldImportance(true), you should either be force unwrapping or returning a Result type, and ensuring someone is actually handling it with a hard stop on the user.
The problem is reality is often much more subtle than "doSomethingImportant()".
For example, I worked on an iOS app that was used for medical work, and one habit iOS devs had was wrapping access to weak references to objects with a null safety:
So they were super comfortable writing things equivalent to viewController?.showSomeDialog()
because in most situations crashing over lifecycle issues is a bad idea... but here we could be creating incorrect output in a highly sensitive situation.
"someDialog" could be "Drug interaction between X and Y detected" for example, but the mental patterns wouldn't detect that a safety operator was hiding that.
It was better for the app to crash than silently hide that information, since at least then it'd be known the app was in an invalid state.
-
Now the problem is here devs start to think "well I'm not making medical apps" or "well I wouldn't make that mistake"...
But go through any moderately large codebase and you will find important user actions that silently fail where a crash would actually serve the user better.
It's how to convince people that a hard crash can ever be good though.
A null phone number would indicate one wasn't found, which could mean the contact record didn't have one, the account didn't have a contact record, or there was no account. If this violates a business rule, then throw a MissingAccount or MissingContact or MissingPhoneNumber exception at the appropriate place that would be more understandable to the end user or could be handled more specifically than a generic null pointer exception.
I'm a C programmer, though, so I'm used to taking the long way around to do things, usually because there's no other choice.
Do you not know why Kotlin exists or why dart added null safety or why C# added null safety? Or were they also wrong in their choices?
Once you start dealing with API + conversion + db, if your language exposse null, it will be painful.
I still wish for ?, ?[] and ?. to offer failsfe for None, IndexError/KeyError and AttributeError one day.
But it has definitely been raised up to The Official Set Of Design Patterns by a lot of people. I've lost count of the number of languages I've seen someone write about "design patterns" in, and what they mean is they show a complete ported implementation of all the GoF design patterns, including all OO quirks, even in languages where they are manifestly inappropriate, including dynamically typed languages (where many of them apply, but are optimally designed quite differently to account for the huge differences in the type system) and functional languages (when many of the GoF patterns just dissolve into the language, but a whole other set of patterns is necessary).
They became misunderstood and abused by enough people that the terms stopped meaning anything useful in public space. When I hear a company say "we're Agile, we are doing REST" etc. I just roll my eyes and think to myself: unlikely.
Over the years I figured out the right way to use all of these things: as resources with solutions to frequent problems.
So no, I will not preach GoF or DDD or CQRS or Agile or REST or anything else, but I will make sure I understood each one very well on many levels and apply the lessons to my projects.
"This book isn't an introduction to object-oriented technology or design. Many books already do a good job of that. This book assumes you are reasonably proficient in at least one object-oriented programming language, and you should have some experience in object-oriented design as well."
At no point it claims to be any kind of software development handbook or complete set of patterns or teaching fundamentals of anything. It is just a collection of "hey guys, see, we figured out this might be useful for ya!".
I was a lowly programmer, invited to a meeting of distinguished engineers and senior staff to review some of the findings from the log collections. When NPEs came up, their comment was that 'there should be zero NPEs' and that they would handle them punitively through reports to managers. So, I asked, "What's your recommendation to the developers to prevent the NPEs?". Silence, nothing. Findbugs existed at the time, and I believe JSR303 was in draft. Happy to report they decided to treat it the same as any other error or bug.
Because they’re just the “type-safe enum” pattern, built in, with some compiler support (e.g. switches). Besides that they’re normal reference types.
> Could have just had some sort of 'default' attribute on a value.
Universal defaults are, if anything, even worse than universal nulls: they generate garbage states you can’t guard against at all.
someEnum = getAnEnumSomewhere(), but at some point there's got to be an original reference being hard-set to null that the compiler could see, right?
also i don't understand your point about universal defaults?
enum Foo { bar default, baz };
why can't you guard against the default? how is checking a foo enum against bar different then checking against null?
https://www.infoq.com/presentations/Null-References-The-Bill...
Just give a real Optional type at a language level. It’s clearly possible in other JVM languages.
Java the language has its flaws, but the frameworks make the situation worse.
> Just give a real Optional type at a language level. It’s clearly possible in other JVM languages.
It's not the presence of Optional that we need, it's the absence of nulls. And nulls are in all the libraries. And you also have to convince your fellow Java developers that null is bad.
What you mean by “at a language level” would break the byte code for jars compiled with older jdks.