-1

Why would I want to manualny create rest controllers for my REST server in Spring boot if ( as showcased in this short video: https://youtu.be/Of1IcjpGNNg) i only need a model and a CRUD repository to make the server work? It seems like Spring automaticaaly generates controllers for all crud methods that can be accessed with POST, GET etc.

Bruno
  • 92
  • 1
  • 8

1 Answers1

0

Because you want to separate responsibilities as much as possible which makes oop like programming. It may be hard to understand when you have proper requirements rather than just basic CRUD operations. But when you have more business logic, more unit tests than it becomes harder to test, maintain and adapt the code. Just to strengthen your understanding, you can start with some basic rules like;

1) A class must have only 1 reason to change.

2) Unit tests should have minimum asserts and verifies

Then It starts makes sense. Think about the scenario, your requirements are changed now business says that they need weather forecast information with every request. So what you are gonna do, after retrieving data from DB, you will make a new Rest request in your same class? Now you have a new layer -> YourService. Even you can have WeatherService layer under the YourService layer. So the responsibilities;

  • Controller Call the YourService, check the exceptions and return the response. It didn't change with new requirements
  • YourService Call other services, retrieve and merge the response and return the merged data
  • WeatherService Call weather API and return the data

So same with the tests. You need minimum assertions in your test;

  • ControllerTest
    • controllerMethod_validRequestParams_shouldCallProperServices
    • controller_whenServiceFails_shouldThrowDummyException

and so on. You can search more with those tags; SOLID principles, DRY, MVC, Clean Coding

cmlonder
  • 2,370
  • 23
  • 35