Shotgun parsing scatters interpretation and validation across code paths. A partially constructed or incompletely validated object crosses boundaries, while later code quietly assumes fields, invariants, and business meaning that were never guaranteed. section 9.6 section 9.2.4
Typical warning signs include:
- A request is validated in one layer, converted into a mutable object in another, and interpreted again by downstream operations. section 9.2.4
- Fields such as sellerId remain nullable even though identity and lookup logic silently requires them. section 9.2.4 section 9.6
- A safer boundary constructs a type only after its invariants hold, making invalid states difficult or impossible to represent. section 9.6
A cart item with hidden requirements
An AddItemsRequest validates productId and quantity, but sellerId is left optional. Cart converts the request into a mutable CartItem, builds a key by concatenating productId and sellerId, and later updates metadata and inventory. The missing sellerId can therefore travel through several methods before causing incorrect identity or behavior. Move the requirement to construction: accept only data that proves the cart item is valid, then let downstream code rely on that guarantee. section 9.2.4
Listing 9.11 Where most of our problems begin
class Cart {
private List<CartItem> active;
...
public void addOrUpdateItems(AddItemsRequest request) {
List<CartItem> items = this.convertToCartItems(request); #A
var activeItemsById = indexBy(this.active, this::qualifiedId)
var savedItemsById = indexBy(this.saved, this::qualifiedId)
for (CartItem incoming : this.active) {
// logic elided
}
...
}
private List<CartItem> convertToCartItems(AddItemsRequest request) {
return request.items().stream().map(external -> {
CartItem item = new CartItem(); #B
item.setProductId(external.getProductId()); #C
item.setSellerId(external.getSellerId()); #C
item.setQuantity(external.getQuantity()); #C
return item; #C
}).toList();
}
}Trace how external request data becomes a mutable CartItem before its full meaning and invariants are enforced. section 9.2.4
