Skip to content

Instantly share code, notes, and snippets.

@soverby
Last active April 18, 2018 22:50
Show Gist options
  • Save soverby/898c6c769a567518379483cc45b39bf7 to your computer and use it in GitHub Desktop.
Save soverby/898c6c769a567518379483cc45b39bf7 to your computer and use it in GitHub Desktop.
// And finally a functional example of the find location with non-zero inventory for item example
public class Functional {
// @Inject
private ItemRepository itemRepository;
// @Inject
private InventoryLocationRepostitory inventoryLocationRepostitory;
// Monadic approach, composed behaviors
// "The monad represents computations with a sequential structure: a monad defines what it means to chain operations together."
public Function<Optional<String>, Optional<InventoryLocation>> firstAvailableLocation = itemIdOpt ->
itemIdOpt.flatMap(itemId ->
itemRepository.findByItemId(itemId)
.flatMap(item ->
inventoryLocationRepostitory
.findByItemId(item)
.filter(inventoryLocation -> inventoryLocation.getInStock() > 0)
.findFirst()));
}
// a few less lines, no null checks, the cruft is basically gone. Didn't bother to unwrap the optiona, we used it!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment