jeudi 30 mars 2023

Is good Idea Apply a generic common functions to all services using interfaces an abstracts?

I am starting a new project using Spring Boot 3. We are still at an early stage of the project and still defining things. so, being said that. Here is my question:

The problem I want to solve: the service layer which is meant to handle all the business logic shares common functions among the entities, eg: CRUD functions and others.

Proposal: Create a Generic interface with all common functions. then: creates an Abstract class that will implement this interface and override; why an Abstract because I want to prevent the paint of adding new functions to the parent interface and going through all the implemented cases.

Here is an example I implemented:

// Project stucture.
main-project
|-src
   |--main
       |-java
          |-com.project
               |-entities
               |-repositories
               |-service
               |    |-implementation    
               |-rest

now We all know what is inside entities, repositories and rest package, here is my service package implementation:

BaseCommonOperationInterface

public interface BaseCommonOperationInterface<E, V> {

  E createItemOf(V requestDto);
  E updateItemfrom(final Long identifier, V requestDto);
  void deleteItem(final Long identifier);
  Optional<E> findSingleRecordByIdentifier(Long skillDicCategoryId);
  List<E> listAllItems();
//more common function...
}

BusinessBaseAbstract

puiblic abstract class BusinessBaseAbstract<E, V> implements BaseCommonOperationInterface<E, V>{
//Here override all methods from interface...
 @Override
  public List<E> listAllItems() {
    return Collections.emptyList();
  }
//...
}

DictionaryService

public interface DictionaryService implement BaseCommonOperationInterface<DictionaryEntity, DictionaryrequestDto>{}

DictionaryServiveImpl


@RequieredArgConstructor
@Service
public class DictionaryServiveImpl extends BusinessBaseAbstract<DictionaryEntity, DictionaryrequestDto> implements DictionaryService{
private final DictionaryRepository dictionaryRepository;

//I can override eather single common function or all of them
@override
public List<DictionaryEntity> listAllItems(){
 return dictionaryRepository.findAll()
}
// all the methods I need overrided here...
}

DictionaryController

@RestController
public class DictionaryController{

private final DictionaryService service;

@GetMapping("/dictionary")
public List<DictionarEntity> getAllofThem(){
return service.listAllItems();
}
//Here rest of implementations...
}

Why no call the DictionaryRepository from the controller beacause we want to keep the Rest Controller clean as much as possible and delegate all business logic to Service package.

Does this pattern make sense? are there advantages and disavantages? are there others pattern that I can apply to abstract common function?

Aucun commentaire:

Enregistrer un commentaire