Skip to content

Instantly share code, notes, and snippets.

@automationhacks
Created February 22, 2020 02:47
Show Gist options
  • Save automationhacks/6b7efb3573a0652d8dbd22634f3e21c6 to your computer and use it in GitHub Desktop.
Save automationhacks/6b7efb3573a0652d8dbd22634f3e21c6 to your computer and use it in GitHub Desktop.
Simple class which models a booking application with booking and cancellation flow
enum class VehicleType() {
CAR,
CAR_XL
}
class BookingNotFound(message: String) : Exception(message)
class Booking {
companion object {
private val bookingDB = hashMapOf<VehicleType, ArrayList<Int>>()
}
init {
bookingDB[VehicleType.CAR] = arrayListOf()
bookingDB[VehicleType.CAR_XL] = arrayListOf()
}
fun makeBooking(type: VehicleType): Int {
val orderId = getRandomInt()
addBookingToDb(type, orderId)
return orderId
}
private fun getRandomInt() = ThreadLocalRandom.current().nextInt(1, 1000)
private fun addBookingToDb(type: VehicleType, orderId: Int) {
bookingDB[type]?.add(orderId)
}
fun cancelBooking(type: VehicleType, orderId: Int) {
val doesOrderExist = doesBookingExists(type, orderId)
cancelBookingIfFound(doesOrderExist, orderId, type)
}
fun doesBookingExists(type: VehicleType, orderId: Int): Boolean? {
return bookingDB[type]?.contains(orderId)
}
private fun cancelBookingIfFound(
doesOrderExist: Boolean?,
orderId: Int,
type: VehicleType
) {
if (doesOrderExist == null) {
throw BookingNotFound("Order $orderId not found in db. Cannot cancel.")
} else {
bookingDB[type]?.remove(orderId)
println("Order <$orderId> successfully removed")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment