#58 Pizza Order Spring Service Review
Refactor the code:
@Component
@Slf4j
public class PizzaSevice {
@Autowired
private UserRepository userRepository;
@Autowired
private PizzaRequestRepository pizzaRequestRepository;
@Autowired
private KitchenService kitchenService;
public UUID requestPizza(UUID userId, PizzaType pizzaType, double price) {
log.info("request pizza: user id = " + userId);
User user = userRepository.getOne(userId);
if ( user == null ) {
return null;
}
PizzaRequest pizzaRequest = new PizzaRequest(UUID.randomUUID());
fillValues(pizzaRequest, price, pizzaType);
saveAndVerify(pizzaRequest);
log.info("request created: pizza id = " + pizzaRequest.getPizzaId());
return pizzaRequest.getPizzaId();
}
public Boolean isPizzaReady(UUID pizzaId) {
log.info("check pizza: id = " + pizzaId);
Optional<PizzaRequest> pizzaRequestOptional = pizzaRequestRepository.findById(pizzaId);
if (pizzaRequestOptional.isPresent()) {
PizzaRequest pizzaRequest = pizzaRequestOptional.get();
try {
PizzaStatus pizzaStatus = kitchenService.getStatus(pizzaRequest);
log.info("status = " + pizzaStatus);
return pizzaStatus == PizzaStatus.READY;
} catch (Exception e) {
return false;
}
} else {
throw new RuntimeException("PizzaRequest not found");
}
}
private void fillValues(PizzaRequest pizzaRequest, double price, PizzaType pizzaType) {
pizzaRequest.setPrice(price);
pizzaRequest.setUserId(userId);
pizzaRequest.setPizzaType(pizzaType);
}
@Transactional
private void saveAndVerify(PizzaRequest pizzaRequest) {
pizzaRequestRepository.save(pizzaRequest);
if (pizzaRequest.getPizzaType() == PizzaType.PEPPERONI) {
throw new RuntimeException("Pepperoni is not available");
}
}
@Entity
@Data
public class PizzaRequest {
private final UUID pizzaId;
private UUID userId;
private PizzaType pizzaType;
private double price;
@ManyToOne(fetch = FetchType.LAZY)
private PizzaMaker pizzaMaker;
}
}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