A construct that I often use in my code is the following:
@RestController
public class HelloController {
@Autowired
private HelloService helloService;
@GetMapping("/hello")
ResponseEntity<Message> getHelloMessage() {
Optional<Message> message = helloService.getMessage();
if (message.isPresent()) {
return ResponseEntity.ok(message.get());
}
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
}
Following DRY principles I abstract this construct away by;
private <T> ResponseEntity<T> response(Optional<T> value) {
if (value.isPresent()) {
return ResponseEntity.ok(value.get());
}
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
So that my code becomes;
@GetMapping("/hello")
ResponseEntity<Message> getHelloMessage() {
return response(helloService.getMessage());
}
It would be very nice if this construct was part of the ResponseEntity class from spring so that my code becomes;
@GetMapping("/hello")
ResponseEntity<Message> getHelloMessage() {
return ResponseEntity.optional(helloService.getMessage());
}
Do you think it is a good idea to implement such a method on ResponseEntity?