3 ms·
That's not true. The Java community in general has known about this for many years, and using Java's `Optional` type for anything nullable has been considered b
by soerxpso 2y ago
That's not true. The Java community in general has known about this for many years, and using Java's `Optional` type for anything nullable has been considered best practice. The reason the language itself has moved slowly is that making core changes to an existing language like this is hard; there are backwards compatibility concerns that are always going to be at odds with correctness concerns, and it's important to hash out the details and make sure that the eventual system they land on is the right one, since it intends to stick around for decades to come.
- mrkeen 2y agoOptionals weren't as well-received as you make them out to be. IntelliJ will issue you a warning for using an Optional either as a field, or a method parameter.
- shepherdjerred 2y agoThe purpose of Optional, IMO, is to avoid returning null, not to avoid receiving null. It is easy to validate incoming params for null or to check if an internal class field is null. It is much harder to know if some method can possibly return null. To put it another way, Optional as a param/field helps the _author_ of the class, Optional as a return helps the _user_ of the class. Taking an Optional as a field/method parameter just introduces a third state you have to handle: * The Optional is present * The Optional is absent * The Optional itself is null I've worked on codebases that abused this where there is different behavior for each of the three cases. On one hand whoever wrote that code should have thought about the contract of their method a bit more. On the other hand, respecting and looking into _why_ IntelliJ is warning about this behavior would help prevent such mistakes in the first place. But, if you really want it, you can configure IntelliJ not to warn on this inspection.
- tadfisher 2y agoThe authors of Optional intended it to only be used as a return type for library functions, to avoid well-known headaches around documenting the nullability of these functions [1]. To quote: > For example, you probably should never use it for something that returns an array of results, or a list of results; instead return an empty array or list. You should almost never use it as a field of something or a method parameter. [1]: https://stackoverflow.com/questions/26327957/should-java-8-getters-return-optional-type/26328555#26328555 https://stackoverflow.com/questions/26327957/should-java-8-g...
- shepherdjerred 2y agoI think we're in agreement. This is exactly how optional should be used.