mardi 28 mars 2023

Design pattern for system retrieving data about an entity and updating it

I've come across the following situation multiple times when writing code (especially webapps) and would like to know the best practice (possibly design patterns) to solve it correctly:

My data is stored in some database or repository where I retrieve the data itself through an API. (therefor needing some sort of GET request)

My retriven data is processed and turned into a object representing the data. Fx a Dog with name, race, age.

In one way or the other I represent this Dog's data on my frontend using classic js, html.

I now want my users to be able to change the data on my frontend, send a request to my backend, and through my backend send a request to the API, updating my database / repository.

This is where my question arises.

What is the best way to structure this processflow? The first naive solution that pops into my head is having a Dog class like the following:

public class Dog() {

 // relevant fields

 public Dog(String json) {
  // map json result to Dog's fields
 }

 public static Dog getDogFromDb() {
  // call api
  // map api's json result to dog object
  // return Dog object
 }
 public void updateDogInDb(credentials, etc) {
  // take current dog, with its id, name, etc. and submit a request to the api, to update it according to Dog's fields and provided credentials.
 }
 // other dog methods, that might be relevant to the context...
 ...
}

In reality the Dog class would be much more complex, containing fields that represent other objects or lists of objects. Fx a Dog could have the following field List<Owner> ownersDogHasHad, this shouldn't change the question I simply want to clarify the complexity.

This approach works in practise, but seems to involve alot of different responsibilities in a single class, since Dog both represents a Dog and its methods, but also the practise of making a dog from a json response.body, making a dog from a database entity, and updating a dog in the databse.

How would this be written in a cleaner and clearer way? Is there any appropriate design patterns relavant?

Aucun commentaire:

Enregistrer un commentaire