Guest User

Untitled

a guest
Apr 25th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. // Somewhere on the road from imperative to functional...
  2. public class PartiallyImperative {
  3. // @Inject
  4. private ItemRepository itemRepository;
  5. // @Inject
  6. private InventoryLocationRepostitory;
  7.  
  8. // Optionally return inventory location with available inventory for item with the given id
  9. public Optional<InventoryLocation> itemByFirstAvailable(String itemId) throws NotFoundException {
  10.  
  11. // Find the item by id optionally - the type safe way of encoding null values.
  12. Optional<Item> itemOptional = itemRepository.findByItemId(itemId);
  13.  
  14. // Unwrap the Item from the Optional or throw not found if the item doesn't exist
  15. Item item = itemOptional.orElseThrow(() -> new NotFoundException("itemId cannot be null"));
  16.  
  17. // Get all known inventory locations for the item
  18. List<InventoryLocation> inventoryLocations = inventoryLocationRepostitory.findByItemId(item);
  19.  
  20. // Optionally return the first inventory location with non-zero inventory
  21. return inventoryLocations.stream()
  22. .filter(inventoryLocation -> inventoryLocation.getInStock() > 0).findFirst();
  23. }
  24. }
  25. // Half the line numbers of the fully imperative version
  26. // What in here is NOT cruft?
  27. // No null checks!!
Add Comment
Please, Sign In to add comment