#58 Pizza Order Spring Service Review

Companies:
Andersen
Themes:
SpringSpring Data JPATransactionsCode Review

Refactor the code:

Java
@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

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