In our Spring Boot app, we use separate endpoints for optional parameters as shown below:
// two methods - not recommended
@GetMapping("/todos/{id}")
public @ResponseBody Todo fetchTodoById(@PathVariable Long id) {
return todoRespository.findById(id);
}
@GetMapping("/todos")
public @ResponseBody List<Todo> fetchAllTodos() {
return todoRespository.findAll();
}
I know that this approach can quickly lead to a large number of (almost) duplicate code-blocks.
To fix this, I can use one of the following approaches:
@GetMapping(value = {"/todos", "/todos/{id}"})
public @ResponseBody Object fetchTodos(@PathVariable(required = false) Long id) {
if (id == null) {
return todoRespository.findById(id);
} else {
return todoRespository.findAll();
}
}
and a similar way using Java Optional
. However, even if it seems better, I think it may be much better to use a separate endpoint. So, which one is proper approach?
CodePudding user response:
- Endpoint
/todos/{id}
returns one ToDo object. - Endpoint
/todos
returns the List of ToDo objects. According to SOLID principle each class or method must do only one thing (return an object or list of objects). So you need to separate methods. I think using optional pathVariable is a bad practice.
CodePudding user response:
I know that this approach can quickly lead to a large number of (almost) duplicate code-blocks.
well it is not exactly true that code is duplicate. The parameter is not exactly separated. The endpoint with the parameter leads to a a given item whereas the second endpoint leads to a list of elements. Even the return type is not the same although you may not see it since you return object.
Therefore, the first method (2 different endpoint handlers) is a far better approach than the second one.