Task: You are asked to review the code of a new feature that allows booking a tour (consisting of a flight ticket and a hotel). The feature for separate booking of a flight ticket and a tour already exists, and this task expects a unified method that books either the entire tour or none of its components.
sobes.tech AI
Answer from AI
To implement a unified tour booking method that either books all components (flight and hotel) or nothing, a transactional approach must be used. This means that the booking should be atomic: if the flight booking is successful but the hotel booking fails, the flight booking must be canceled.
In C#, this can be implemented using the "Transaction" pattern or by using transaction management mechanisms if the booking is done through databases or external services that support rollback.
An approximate approach:
public class BookingService
{
private readonly FlightService _flightService;
private readonly HotelService _hotelService;
public BookingService(FlightService flightService, HotelService hotelService)
{
_flightService = flightService;
_hotelService = hotelService;
}
public bool BookTour(TourRequest request)
{
var flightBookingId = _flightService.BookFlight(request.FlightDetails);
if (flightBookingId == null)
return false;
var hotelBookingId = _hotelService.BookHotel(request.HotelDetails);
if (hotelBookingId == null)
{
_flightService.CancelBooking(flightBookingId); // Rollback flight booking
return false;
}
return true;
}
}
Thus, if the hotel booking fails, the flight booking is canceled, ensuring the operation's integrity. In real-world conditions, exception handling, timeouts, and potential issues with consistency when working with external services should be considered.