Skip to content

Instantly share code, notes, and snippets.

@davidseek
Last active February 8, 2021 03:28
Show Gist options
  • Save davidseek/83c96f79f953bd09bb745eba597e7810 to your computer and use it in GitHub Desktop.
Save davidseek/83c96f79f953bd09bb745eba597e7810 to your computer and use it in GitHub Desktop.
hotelOptimized.swift
class Hotel {
// MARK: - Public
// Another major improvement in our design,
// is to clearly define the desired access level of a function.
// We mark this function as public, as we want
// consumers to be able to access this function.
public func checkIn(_ dog: Dog) -> String? {
// Declare a nil roomID
var roomID: String?
// In the new design we're going to
// try to get a roomID from a private method
// This function is not async!
// This function is just written with a closure,
// because we're returns a reference.
// That's the inout equivalent of returns.
getRooms(for: dog) { rooms in
// If we have rooms, then we want to create an ID
roomID = UUID().uuidString
// Assign the dog to that room
rooms[roomID!] = dog
}
// And lastly return the ID.
return roomID
}
// MARK: - Private
// To define a clear API for consumers of our object,
// we're going to set the access level of this function to private.
// No one outside of this class needs access to it.
// The function executes syncronous and utilizes a closure
// to return the reference of the available sizes dictionary.
//
// It's possible to optimize or further refactor this function.
// But you need to think small when it comes to those kind of details.
// You typically got less than 20 mins for implementation.
private func getRooms(for dog: Dog, result: (inout [String: Dog]) -> Void) {
// For large dogs we can only return large rooms.
// They won't fit into the smaller rooms.
// #PETA.
if dog.size == .large, largeRooms.keys.count < largeRoomsCount {
// If we have availability,
// complete with the reference to the rooms dictionary.
result(&largeRooms)
}
// For medium sized dogs...
if dog.size == .medium {
// We can use medium sized rooms...
if mediumRooms.keys.count < mediumRoomsCount {
result(&mediumRooms)
}
// As well as large rooms.
if largeRooms.keys.count < largeRoomsCount {
result(&largeRooms)
}
}
// For small dogs...
if dog.size == .small {
// Small..
if smallRooms.keys.count < smallRoomsCount {
result(&smallRooms)
}
// Medium..
if mediumRooms.keys.count < mediumRoomsCount {
result(&mediumRooms)
}
// And large...
if largeRooms.keys.count < largeRoomsCount {
result(&largeRooms)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment