[JAVA-674] Add more fluent methods like appendIfNotNull() to BasicDBObject Created: 23/Oct/12  Updated: 08/Nov/17  Resolved: 08/Nov/17

Status: Closed
Project: Java Driver
Component/s: API
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Major - P3
Reporter: Christian Brensing Assignee: Unassigned
Resolution: Won't Fix Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Backwards Compatibility: Fully Compatible

 Description   

BasicDBObject already has a fluent method append(String key, Object val) returning itself. It would be very convenient to have more append methods like

  • BasicDBObject appendIfNotBlank(String key, String val)
  • BasicDBObject appendIfNotEmpty(String key, Collection val)
  • BasicDBObject appendIfNotEmpty(String key, Object[] val)
  • BasicDBObject appendIfNotEmpty(String key, String val)
  • BasicDBObject appendIfNotNull(String key, Object val)

so that you could write code like this:

DBObject dbo = new BasicDBObject()
        .append("k1", 42)
        .appendIfNotNull("k2", somePossiblyNullValue)
        .appendIfNotBlank("k3", somePossiblyBlankString)
        .appendIfNotEmpty("k4", somePossiblyEmptyString)
        .appendIfNotEmpty("k5", somePossibleEmptyCollection)
        .appendIfNotEmpty("k6", somePossibleEmptyArray)

instead of

DBObject dbo = new BasicDBObject();
if (somePossibleNullValue != null) {
    dbo.put("k2, somePossibleNullValue);
}
if (somePossibleEmptyCollection != null && !somePossibleEmptyCollection.isEmpty()) {
    dbo.put("k5", somePossibleEmptyCollection)
}
...



 Comments   
Comment by Jeffrey Yemin [ 08/Nov/17 ]

We're not investing any more in the BasicDBObject API as org.bson.Document is now preferred. If anyone is still interested in a feature like this for org.bson.Document please open a new ticket.

Comment by Christian Brensing [ 23/Oct/12 ]

The implementation of these fluent methods should be as simple as

public BasicDBObject appendIfNotBlank(String key, String val) {
    if (val != null && !val.trim().isEmpty()) {
        put(key, val);
    }
    return this;
}
 
public BasicDBObject appendIfNotEmpty(String key, Collection val) {
    if (val != null && !val.isEmpty()) {
        put(key, val);
    }
    return this;
}
 
public BasicDBObject appendIfNotEmpty(String key, Object[] val) {
    if (val != null && val.length > 0) {
        put(key, val);
    }
    return this;
}
 
public BasicDBObject appendIfNotEmpty(String key, String val) {
    if (val != null && !val.isEmpty()) {
        put(key, val);
    }
    return this;
}
 
public BasicDBObject appendIfNotNull(String key, Object val) {
    if (val != null) {
        put(key, val);
    }
    return this;
}

Generated at Thu Feb 08 08:52:49 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.