Composition over Inheritance
The problem
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/")
public class Controller extends Service {
@GetMapping("users")
public ResponseEntity<List<User>> users() {
return ResponseEntity.ok(getUsers());
}
}
class Service extends Repository {
List<User> getUsers() {
List<String> users = super.findUsers();
return users.stream().map(User::new).collect(Collectors.toList());
}
}
class User {
private final String name;
User(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class Repository {
List<String> findUsers() {
ArrayList<String> users = new ArrayList<>();
users.add("John");
return users;
}
}Solution
Last updated