[ https://issues.apache.org/jira/browse/SLING-8706?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17142358#comment-17142358 ]
Paul Bjorkstrand commented on SLING-8706: ----------------------------------------- I agree with [~justinedelson] on the HTL side. Just because Sling Models supports this feature doesn't make it required to be supported in HTL (though, only one supporting with the other not supporting {{Optional}} could lead to some confusion). I also have never seen any (Java) serialization of Sling Models, so I don't see that as a barrier either. Besides, serialization [can be customized|https://howtodoinjava.com/java/serialization/custom-serialization-readobject-writeobject/] ([in more than one way|https://dzone.com/articles/how-to-customize-serialization-in-java-using-the-e]) to work around non-serializable types already. Based on the intended use of {{Optional}} (to be used at API boundaries aka method returns), this I feel is a gray area. While a field isn't technically part of an API, they are injected by some external process. One could argue that the fields are equivalent to the return values of that external process. In that argument, it makes sense to capture that intent in the type system itself, to capture the fact that "this field could be null, so you need to check it". This alone makes me think this is a reasonable approach to handling optional injections. That being said, there is nothing stopping a developer from improperly using an {{Optional}}, say, by using {{.get()}} without first checking {{.isPresent()}}, in turn causing a NPE. While bad practice, yes, it happens frequently enough that I almost always have a conversation with my teams on proper {{Optional}} usage. I still believe this idea is reasonable, but I don't buy into the "optional will prevent NPEs" argument. > Injections for java.util.Optional<> should be automatic optional > ----------------------------------------------------------------- > > Key: SLING-8706 > URL: https://issues.apache.org/jira/browse/SLING-8706 > Project: Sling > Issue Type: Improvement > Components: Sling Models > Reporter: Jörg Hoh > Priority: Major > Time Spent: 2h 40m > Remaining Estimate: 0h > > The current approach to support optional injections requires to annotate the > field with {{@Optional}} plus proper handling within the javacode (null > checks etc), which can be forgotten. > So instead of > {code} > @Inject @Optional > String fieldname; > {code} > it should also be possible to use this > {code} > @Inject > Optional<String> fieldname; > {code} > with the very same semantic. But the developer is forced to deal with the > case that the value is not present. -- This message was sent by Atlassian Jira (v8.3.4#803005)