Last active
April 18, 2018 22:49
-
-
Save soverby/8612a93bfccaf407109a9ce85288dc54 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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