Use Java 8 Optionals in addition to is/as

XMLWordPrintableJSON

    • Type: Improvement
    • Resolution: Unresolved
    • Priority: Minor - P4
    • None
    • Affects Version/s: None
    • Component/s: BSON
    • None
    • None
    • Java Drivers
    • None
    • None
    • None
    • None
    • None
    • None

      Because BsonValue has boolean is methods, and throwing as methods, a common pattern is:

      BsonValue value;
      if (value.isSomeType()) {  
        BsonSomeType valueSomeType = value.asSomeType();  
        // .. operate on valueSomeType
      }
      

       
      Nested conditionals are even harder:

      BsonValue value;
      if (value.isDocument() && value.asDocument().get("key").isInt32()) {  
        //... dig in and get it
      }
      

       
      By using Java 8's Optional, we can simplify these with a fluent syntax:

      BsonValue value;
      value.asSomeTypeOpt().ifPresent(valueSomeType => {
        // valueSomeType is guaranteed to be BsonSomeType
      });
      
      Optional<BsonInt32> nested = value.asDocumentOpt()
        .flatMap(doc => doc.get("key").asInt32Opt());
      
      

       
      I can also add get*Opt methods to BsonDocument if they make sense.

              Assignee:
              Unassigned
              Reporter:
              Jeff Alder (Inactive)
              None
              Votes:
              0 Vote for this issue
              Watchers:
              5 Start watching this issue

                Created:
                Updated: