Uploaded image for project: 'Sling'
  1. Sling
  2. SLING-8758

Add Adaptable method with a non-null return value

    XMLWordPrintableJSON

    Details

    • Type: Improvement
    • Status: Closed
    • Priority: Major
    • Resolution: Duplicate
    • Affects Version/s: None
    • Fix Version/s: None
    • Component/s: API
    • Labels:
      None

      Description

      We have had long-standing discussions about the fact that adaptTo returning null can lead to many hard-to-trace bugs.

      One option of evolving the API is to add a default method to the adaptable which returns an optional

          default @NotNull <AdapterType> Optional<AdapterType> tryAdapt(@NotNull Class<AdapterType> type) {
              return Optional.ofNullable(adaptTo(type));
          }
      

      This can in turn be used by clients to check that the adaption succeeed in a more fluent way

      MyAdapted resource = resource.tryAdapt(MyAdapted.class)
                  .orElseThrow( () -> new RuntimeException("Adaption failed") )
                  .get();

      or enable functional API usage patterns

      MyAdapted resource = resource.tryAdapt(MyAdapted.class)
              .ifPresent( a ->  consume(a) );
      

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                rombert Robert Munteanu
              • Votes:
                0 Vote for this issue
                Watchers:
                3 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: