vendredi 20 mai 2022

Navigate in object with a lot of nulls

I'm trying to implement a good design in my code. There is a Entity purchaseOrder and I need to navigate inside that object that has a list of stockOrder and each StockOrder has a list of StockOrderItem. There is no guarantee that a stockOrder or stockOrderItem exists so I needed to check a lot of nulls. Is there a elegant way to do that?

        PurchaseOrder purchaseOrder = purchaseOrderRepository.
            findByIdentifierAndBrandId(po.getPurchaseOrderIdentifier(), po.getBrandId());
        List<StockOrder> stockOrders = Optional.ofNullable(
            purchaseOrder.getStockOrders()).orElse(Collections.emptyList());
        for (StockOrder stockOrder : stockOrders) {
            for (StockOrderItem stockOrderItem : Optional.
                ofNullable(stockOrder.getStockOrderItems()).orElse(Collections.emptyList())) {
                InventoryDataLoad inventoryDataload = new InventoryDataLoad();
                inventoryDataload.setSku(stockOrderItem.getSku());
                inventoryDataLoadList.add(inventoryDataload);
            }
        }

Aucun commentaire:

Enregistrer un commentaire