gvsucis / mobile-app-dev-book

Sample code for the Engelsma/Dulimarta Mobile App Dev book.
GNU General Public License v3.0
18 stars 5 forks source link

Listing 6.1 - Parameter size #6

Closed jocmp closed 3 months ago

jocmp commented 7 years ago

Location: Page 189, 190, Listing 6.1, Listing 6.2 Git Commit: be9b0cf Issue: The length of parameters in both of the Journal constructors is a candidate for a builder method. By implementing a design pattern, it would reflect a real-world task of implementing multiple representations of an object.

According to GOF:

Use the Builder pattern when

  • the construction process must allow different representations for the object that's constructed

References

For example

struct Journal {

    let key: String?
    let name: String?
    let location: String?
    let startDate: Date?
    let endDate: Date?
    let lat: Double?
    let lng: Double?
    let placeId: String?

    fileprivate init(builder: Builder) {
        key = builder.key
        name = builder.name
        location = builder.location
        startDate = builder.startDate
        endDate = builder.endDate
        lat = builder.lat
        lng = builder.lng
        placeId = builder.placeId
    }

    class Builder {

        var key: String?
        var name: String?
        var location: String?
        var startDate: Date?
        var endDate: Date?
        var lat: Double?
        var lng: Double?
        var placeId: String?

        func key(key: String) -> Builder {
            self.key = key
            return self
        }

        func name(name: String) -> Builder {
            self.name = name
            return self
        }

        func location(location: String) -> Builder  {
            self.location = location
            return self
        }

        func startDate(date: Date) -> Builder  {
            startDate = date
            return self
        }

        func endDate(date: Date) -> Builder  {
            endDate = date
            return self
        }

        func coordinates(latitude lat: Double, longitude lng: Double) -> Builder {
            self.lat = lat
            self.lng = lng
            return self
        }

        func placeId(placeId: String) -> Builder {
            self.placeId = placeId
            return self
        }

        func build() -> Journal {
            return Journal(builder: self)
        }
    }
}

Calling the builder class

let journal = Journal.Builder().name(name: "Out West")
    .location(location: "Estes Park, Co")
    .startDate(date: Date.distantFuture)
    .endDate(date: Date.init(timeInterval: 100000, since: Date.distantFuture))
    .coordinates(latitude: 40.3772059, longitude: -105.5216651)
    .placeId(placeId: "ChIJAxoZu9ZlaYcRDKzKqbeYlts")
    .build()

print(journal.location!) // -> "Estes Park, Co\n"