title: Different return types for function Java
body: <p>I'm using Spring Boot with Data JPA.<br>
  I have the following code. </p>
  
  <p>A User Class with name and an informative message.</p>
  
  <pre><code>    class UserResponse{
         private String name;
         private String message;
      }  
  </code></pre>
  
  <p>User JPA Repository which finds userBy id;  </p>
  
  <pre><code>    interface UserRepository{
         Optional&lt;User&gt; findUserById(String id);
      }
  </code></pre>
  
  <p>User Service which invokes repo and set message if user not found</p>
  
  <pre><code>    class UserService(){
         UserResponse user = new UserResponse();
         public UserResponse getUserById(String userId){
         Optional&lt;User&gt; useroptional = userRepository.findById(userId);
         if(userOptional.isPresent()){
          user.setName(userOptional.get().getName());
         }else{
          user.setMessage("User Not Found");
         }
      }
  </code></pre>
  
  <p>UserController has to set proper HTTP status code as per the message.</p>
  
  <pre><code> class UserController(){
         public ResponseEntity&lt;UserResponse&gt; getUserById(String id){
          UserResponse user = userService.getUserById(id);
          HttpStatus status = OK;
          if(!StringUtils.isEmpty(user.getMessage())){
            status = NOT_FOUND;
          }
           return new ResponseEntity&lt;&gt;(user,status);
         }
      }
  </code></pre>
  
  <p>The problems I have faced is inorder to set proper status code in controller layer I have to inspect user message,which i didn't like.
  Is there anyway we can create a control flow for Success and Failure cases.</p>
  
  <p>Say One Return type and flow for Success scenario and vice-versa.
  I know Scala has this feature with <strong>Either</strong> keyword.
  Is there any alternate in Java ?
  Or any other approach I can use to handle this better...<br>
  One approach would be returning RepsonseEntity in service layer itself with proper status code but setting status code is controller's Responsibility is what I felt.</p>