vendredi 24 février 2023

Java Design/Spring Boot question, how to break down responsibilities inside a Service

Lets say you have a business flow that evolves around creating multiple queries on a songs database, and you have some steps in all

The example is in Spring Boot but the logic can be applied anywhere

  1. Have a factory that decides the query
  2. Parse: Receive some data, break them down, create the query
  3. Query: Perform query on repository, the query returns a List<SongItem>
  4. PrepareAnswer: Create a return DTO

Steps 2, 4, have different implementations, thus the different classes

you can create an interface or abstract class Query

private interface Query(){
    public ?? parse();
    public QueryBuilder createQuery();
    public ?? PrepareAnser();
}

and implement multiple Query types like RockQuery PopQuery FolkQuery

public class RockQuery implements Query

How should the service be organized and the data List<SongItem> carried around the several steps?

I have several thoughs, its mostly wether to include the SongList in the class or keep it in the Service

1)

@Service
public class SongService()

public SongListDTO makeAList(Data data){
    
    @Autowired
    SongRepository repository;
    
    Query query = factory(data).getQuery(Type.ROCK); // or something similar
    List<SongItem> songs = repository.query(query.createQuery());
    return query.prepareAnswer(songs);
    
}

    instead of creating a different querytype, actually perform the query inside the QueryClass, not the Service. Of course inject the repository there.

    Keep the List<SongItem> as class member. Dont expose it to the Service

    public SongListDTO makeAList(Data data){
        Query query = factory(data).getQuery(Type.ROCK); // or something similar
        query.performQuery()
        return query.prepareAnswer(songs);
    }
    
    1. Something similar, multiple variations may apply

    Aucun commentaire:

    Enregistrer un commentaire