Z
Z
ZavkHozz7772020-05-19 18:40:12
Java
ZavkHozz777, 2020-05-19 18:40:12

Is there a method for handling unrelated objects?

There is a program for saving Car objects in the database. We need to add the ability to save and process objects of the Airplane type, and we also need to do refactoring, add the ability to process other Collateral-derived types.
The incoming Collateral object is cast to the appropriate type and the methods of its corresponding Service implementation (carService, airplaneService, etc.) are applied to it. How can this whole process be automated?
You can write similar saveCollateral and getInfo for AirplaneDto, but you get code duplication and when adding other types of objects, you will have to write a bunch of code again

Help....

// TODO: reimplement this
@Service
public class CollateralService {
    /* CarService - интерфейс, реализуемый классом CarServiceImpl
    в котором создается адаптер для входящего CarDto и реализуются 
    все методы, вызываемые в этом сервисе
     */
    @Autowired
    private CarService carService;
    
    @SuppressWarnings("ConstantConditions")
    public Long saveCollateral(Collateral object) {

        if (!(object instanceof CarDto)) {
            throw new IllegalArgumentException();
        }

        /*CarDto - наследует Collateral*/
        CarDto car = (CarDto) object;
        /* 
        Метод carService.approve() создает адаптер класса
        CarDto и отправляет на проверку в соответствующий сервис.
        Перед сохранением все объекты должны пройти проверку
        */
        boolean approved = carService.approve(car);
        if (!approved) {
            return null;
        }

        return Optional.of(car)
                .map(carService::fromDto)
                .map(carService::save)
                .map(carService::getId)
                .orElse(null);
    }

    public Collateral getInfo(Collateral object) {
        if (!(object instanceof CarDto)) {
            throw new IllegalArgumentException();
        }

        return Optional.of((CarDto) object)
                .map(carService::fromDto)
                .map(carService::getId)
                .flatMap(carService::load)
                .map(carService::toDTO)
                .orElse(null);
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question