You don't seem to need to #map
here, as if the Optional
s are empty, you want exceptions to be thrown:
// this should probably live in the service layer instead of the controller layer:
public Record setAnimalHappy(String id, Record animalRecord) {
Person person = personRepository
.findById(id)
.orElseThrow(PersonException::new);
// the following might be replaced by recordService.findById(animalRecord.getId()),
// while making sure the returned record belongs to `person`:
Record record = person
.getRecordList()
.stream() // don't use parallel streams (unless you know what you're doing)
.filter(record -> record.getId().equals(animalRecord.getId()))
.findFirst()
.orElseThrow(RecordException::new);
// not 100% sure the 2 following lines behave the way you'd expect:
record.getAnimalStatus().setHappy(true);
personRepository.save(person);
return record;
}
Business logic apart, something along those lines might be arguably more readable.
It's easy to lose yourself into callbacks when entering the functional programing world. One rule I tend to follow, is "don't use -> {
" (multiline lambda expressions): either reorganise your code (like the above example), or use additional functions to improve readability.
Interesting related read: https://dzone.com/articles/functional-programming-patterns-with-java-8.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…