From 098cd1651490248ba63a4ba0eccb222ec5ab4956 Mon Sep 17 00:00:00 2001 From: fanatixan Date: Sat, 16 Jun 2018 15:22:42 +0200 Subject: [PATCH] simplify controller method --- .../annotations/CustomResponseController.java | 29 ++++++++++++------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/CustomResponseController.java b/spring-mvc-java/src/main/java/com/baeldung/annotations/CustomResponseController.java index de41adb13b..a29a6252f2 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/annotations/CustomResponseController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/annotations/CustomResponseController.java @@ -24,30 +24,39 @@ public class CustomResponseController { @GetMapping("/age") public ResponseEntity age(@RequestParam("yearOfBirth") int yearOfBirth) { - int currentYear = Year.now().getValue(); - - if (currentYear < yearOfBirth) { + if (isInFuture(yearOfBirth)) { return new ResponseEntity<>("Year of birth cannot be in the future", HttpStatus.BAD_REQUEST); } - int age = currentYear - yearOfBirth; - - return new ResponseEntity<>("Your age is " + age, HttpStatus.OK); + return new ResponseEntity<>("Your age is " + calculateAge(yearOfBirth), HttpStatus.OK); } - + + private int calculateAge(int yearOfBirth) { + return currentYear() - yearOfBirth; + } + + private boolean isInFuture(int year) { + return currentYear() < year; + } + + private int currentYear() { + return Year.now().getValue(); + } + @GetMapping("/customHeader") public ResponseEntity customHeader() { HttpHeaders headers = new HttpHeaders(); headers.add("Custom-Header", "foo"); - + return new ResponseEntity<>("Custom header set", headers, HttpStatus.OK); } - + @GetMapping("/manual") public void manual(HttpServletResponse response) throws IOException { response.setHeader("Custom-Header", "foo"); response.setStatus(200); - response.getWriter().println("Hello World!"); + response.getWriter() + .println("Hello World!"); } }