-
Type: Improvement
-
Resolution: Unresolved
-
Priority: 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.