Uploaded image for project: 'Java Driver'
  1. Java Driver
  2. JAVA-5563

Use Java 8 Optionals in addition to is/as

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

      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 Unassigned
            Reporter:
            jeff.alder@mongodb.com Jeff Alder
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated: