Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The 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.



The 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-g...


I think we're in agreement. This is exactly how optional should be used.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: