user1224036 user1224036 - 2 months ago 8
Java Question

Java 8 service calls and functional constructs

I am trying to learn Java 8, I have Cat, Food, CurrentState, Outcome domain objects and catService, foodService, outcomeService. So my method looks like this

public class Cat {
private Long ownerId;
private Long Id;

public Long getOwnerId() {
return ownerId;
}

public void setOwnerId(Long ownerId) {
this.ownerId = ownerId;
}

public Long getId() {
return Id;
}

public void setId(Long id) {
Id = id;
}

public CurrentState findActiveCurrentState() {
return new CurrentState();
}

}

class CurrentState {
Long outcomeId;

public Long getOutcomeId() {
return outcomeId;
}

public void setOutcomeId(Long outcomeId) {
this.outcomeId = outcomeId;
}

Outcome findByOutcomeId(Long outcomeId) {
return new Outcome();
}
}

class Food {

}

class Outcome {
Long outcomeId;
List<String> types;

public List<String> getTypes() {
types = new ArrayList<>();
types.add("Food");
types.add("Bath");
return types;
}

public void setTypes(List<String> types) {
this.types = types;
}
}


class CatService {
Optional<Cat> findByOwnerId(Long ownerId) {
return Optional.of(new Cat());
}

public void eatFood(Food food) {

}
}

class FoodService {
Food find(Long catId) {
return new Food();
}

class FoodEventService {

private CatService catService = new CatService();

private FoodService foodService = new FoodService();

public void processCatCanEatFoodEvent(Long ownerId) {
Optional<Cat> cat = catService.findByOwnerId(ownerId);
if (cat.isPresent()) {
//dont worry about the findActiveCurrentState(),its not really important
CurrentState currentState = cat.get().findActiveCurrentState();
Food food = foodService.find(cat.get().getId());
Outcome outCome = currentState.findByOutcomeId(currentState.getOutcomeId());

if (outCome.getTypes().contains("Food")) {
catService.eatFood(food);
}


}
}
}

}


i tried to abstract each of those service calls to a function and then use compose and andThen, but not sure whether it will work or its the right way. So any help would be appreciated, so i am looking to refactor processCatCanEatFoodEvent method. as you asked in the comment updated the class.

Answer

The rule of thumb I’ve learned about Optionals is “never use get()”. In your case, since you already have the if statement, it’s not that hard to find something a bit more elegant:

        cat.ifPresent(c -> {
            CurrentState currentState = c.findActiveCurrentState();
            Food food = foodService.find(c.getId());
            Outcome outCome = currentState.findByOutcomeId(currentState.getOutcomeId());

            if (outCome.getTypes().contains("Food")) {
                catService.eatFood(food);
            }
        });

For your question, after playing around a bit I tend to agree with Louis Wasserman, there’s no real point in introducing consumers, compose() and andThen().

Comments