#30 Refactoring a Stateful Service into a Stateless One
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
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor