Filter facility visits returned by Census endpoint.
. . .
. . .
1 visit : 2 DB queries
2 visits: 4 DB queries
3 visits: 27 DB queries
4 visits: ~100 DB queries
5 visits: ~250 DB queries
Function that takes a single T and returns a boolean
List<Entity> unfilteredItems;
Predicate<Entity> requiresPermission =
(entity) ->
logic.sensitiveFields(unfilteredItems).matches(entity);
List<Entity> privateData =
unfilteredItems
.filter(requiresPermission);
List<Entity> privateData(List<Entity> unfilteredItems) {
Predicate<Entity> requiresPermission =
(entity) ->
logic.sensitiveFields(unfilteredItems).matches(entity);
return
unfilteredItems
.filter(requiresPermission);
}
privateData(List<Entity> unfilteredItems) {
(entity) ->
logic.sensitiveFields(unfilteredItems)
}
Call sensitiveFields for each item. Use it once.
Call sensitiveFields once. Use it for all entities.
Predicate<Entity> requiresPermission =
(entity) ->
logic.sensitiveFields(unfilteredItems).matches(entity);
Predicate<Entity> requiresPermission =
logic.sensitiveFields(unfilteredItems)::matches;
Validator validator =
logic.sensitiveFields(unfilteredItems)
Predicate<Entity> requiresPermission =
(entity) ->
validator.matches(entity);
List<Entity> endpoint(List<Entity> bulkItems) {
Predicate<Entity> otherPredicate = ...
Predicate<Entity> primaryRequirement =
(entity) ->
logic.allowed(bulkItems).contains(entity);
return
bulkItems
.filter(primaryRequirement.or(otherPredicate);
}
endpoint(List<Entity> bulkItems) {
(entity) ->
logic.allowed(bulkItems)
}
2 methods below my code queried the DB
FacilityLogic
Facility get(String facilityId) {
try {
return DB.getFacility(facilityId);
} catch (HorribleDbException ex) {
log.error("Error getting facility");
return null; // Everything is totally fine!
}
}
FacilityConfigLogic
String configByName(Facility facility, String configName) {
try { // facility is null!
return DB.getConfig(facility, configName);
} catch (NullPointException ex) {
log.("Can't get value for facility", facility);
return null; // Just keep swimming
}
}
Don’t pass collections into lambdas that will be applied to that same collection.
(Don’t nest loops.)
Accept defeat when you encounter a fatal Exception.
(Don’t swallow Exceptions)
If you don’t have a test that can trigger the original problem, you don’t truly know what’s wrong.
(Create a failing test before writing the “fix”)