Skip to content

Instantly share code, notes, and snippets.

@soverby
Last active April 18, 2018 22:49
Show Gist options
  • Save soverby/8612a93bfccaf407109a9ce85288dc54 to your computer and use it in GitHub Desktop.
Save soverby/8612a93bfccaf407109a9ce85288dc54 to your computer and use it in GitHub Desktop.
// Somewhere on the road from imperative to functional...
public class PartiallyImperative {
// @Inject
private ItemRepository itemRepository;
// @Inject
private InventoryLocationRepostitory;
// Optionally return inventory location with available inventory for item with the given id
public Optional<InventoryLocation> itemByFirstAvailable(String itemId) throws NotFoundException {
// Find the item by id optionally - the type safe way of encoding null values.
Optional<Item> itemOptional = itemRepository.findByItemId(itemId);
// Unwrap the Item from the Optional or throw not found if the item doesn't exist
Item item = itemOptional.orElseThrow(() -> new NotFoundException("itemId cannot be null"));
// Get all known inventory locations for the item
List<InventoryLocation> inventoryLocations = inventoryLocationRepostitory.findByItemId(item);
// Optionally return the first inventory location with non-zero inventory
return inventoryLocations.stream()
.filter(inventoryLocation -> inventoryLocation.getInStock() > 0).findFirst();
}
}
// Half the line numbers of the fully imperative version
// What in here is NOT cruft?
// No null checks!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment