#268 Code Review of a Ticket Creation Service

Companies:
Innotech
Themes:
SpringTransactionsCode Review

Perform a code review:

@Service
class TicketService {

    @Autowired
    public UserRepository userRepository;

    @Autowired
    public TicketRepository ticketRepository;

    @Autowired
    private NotificationService notificationService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Transactional(
            propagation = Propagation.REQUIRES_NEW,
            isolation = Isolation.REPEATABLE_READ
    )
    public String createTicket(String username, String password, String content) {
        Collection<Ticket> tickets = ticketRepository.findByUsername(username);

        boolean canCreateTicket = true;

        for (Ticket ticket : tickets) {
            if ("OPEN" == ticket.getStatus()) {
                canCreateTicket = false;
            }
        }

        if (!canCreateTicket) {
            return "Can not create ticket";
        }

        long newTicketId = tickets.stream()
                .map(Ticket::getId)
                .max(Long::compare)
                .map(maxTicketId -> maxTicketId + 1)
                .orElse(1L);

        Optional<User> userOptional = userRepository.findByUsernameAndPassword(username, password);

        if (userOptional.get() == null) {
            return "User not found or password is incorrect";
        }

        User user = userOptional.get();

        Ticket newTicket = new Ticket(newTicketId, user, "OPEN", content);

        ticketRepository.save(newTicket);

        notificationService.sendNotification(newTicketId);

        jdbcTemplate.execute(
                ("INSERT INTO public.ticket_history (ticket_id, status, created_by, created_at) "
                        + "VALUES (%d, '%s', '%s', CURRENT_TIMESTAMP)")
                        .formatted(newTicket.getId(), "OPEN", username)
        );

        return "OK";
    }
}

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