#30 Refactoring a Stateful Service into a Stateless One

Companies:
Alfa-Bank
Themes:
SpringSpring BootPractice

Refactor the code:

@RestController
@RequestMapping(path = "/contract")
public class ContractController {

    private final ContractRepository repository;
    private final ContractService contractService;

    public ContractController(ContractRepository repository, ContractService contractService) {
        this.repository = repository;
        this.contractService = contractService;
    }

    @PostMapping(path = "/{contractId}/price")
    public void updatePrice(@PathVariable Long contractId) {
        Contract contract = repository.findById(contractId).orElseThrow();
        contractService.setContract(contract);
        contractService.updatePrice();
}
}

@Service
public class ContractService {

    private final PriceService priceService;
    private Contract contract;

    public ContractService(PriceService priceService) {
        this.priceService = priceService;
    }

    public void setContract(Contract contract) {
        this.contract = contract;
    }

    public void updatePrice() {
        if (contract != null) {
            BigDecimal price = priceService.calcPrice(contract);
            contract.setPrice(price);
        }
    }
}

class Contract {

    private BigDecimal price;

    public BigDecimal getPrice() {
        return this.price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }
}

Question review

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in