3 ms·
This is more or less how my teams' back end REST API server code is written as well. It's far, far superior to the idiotic God classes most Java devs tend to w
by bedobi 5y ago
This is more or less how my teams' back end REST API server code is written as well.
It's far, far superior to the idiotic God classes most Java devs tend to write - the ones covered in attributes that are sometimes populated, other times not, and annotations for ten different purposes. Just no. Don't use the same single class to parse incoming requests, persist records at the innermost db layer, serializing the outgoing json etc etc etc.
The sane way to do it is to have a dedicated class to parse incoming requests, another dedicated class that represents a validated and decorated record to be persisted (that doesn't have an id attribute, because it hasn't been persisted yet), another that represents a persisted record (with an id now, that is guaranteed to never be null), another that represents the outgoing response etc etc.
A common criticism of this style is that it's wordier, there are too many types, and it can be hard to follow if you're not used to it. The thing is, that's the price you pay for more accurately modelling what's actually going on at each step. The "use a single God class for everything" alternative is "easy to follow" only because it omits important differences that are actually there at each step, which doesn't mean they're not there - they are there, they're just hidden.
- stank345 5y agoI feel the same way. Much better to encode the complexity of what you're modeling in types instead of ignoring the inherent complexity. By precisely encoding the shape of the data in types you are forced to engage with the values it can represent which leads to better understanding and better code in my experience, similar to how writing tests can lead to better code, except it's much faster to get feedback.
- BiteCode_dev 5y agoThat's basically how most modern frameworks do it. Django-Rest-Framework does that with view + serializer + validators. A more recent example, with a leaner and cooler implementation is FastAPI, where type hints are also use to declare validation on your end point, while a model is used for serializing the response.