vendredi 17 novembre 2023

Is there an advantage to hiding the model layer?

I was looking at a tutorial on the MVVM architecture pattern.

It says that views should never have direct access to the model. So all views are always hidden behind a view model.

For example:

Model

struct Location: Codable, Equatable {

//MARK: Properties

let id: String
let name: String
let country: String

//
let latitude: Double
let longitude: Double

init(id: String, name: String, country: String, latitude: Double, longitude: Double) {
    self.id = id
    self.name = name
    self.country = country
    self.latitude = latitude
    self.longitude = longitude
}
}

View Model that hide the model layer

final class LocationCellViewModel: Identifiable {

//MARK: Properties

private let location: Location

//
var locationViewModel: LocationViewModel {
    .init(location: location)
}

// MARK: - Initialization

init(location: Location) {
    self.location = location
}

// MARK: - Public API

var locationName: String {
    location.name
}

var locationCountry: String {
    location.country
}

....

}

View Model that will be in the view as property

final class LocationsViewModel {

//MARK: Properties

private(set) var locationCellViewModels: [LocationCellViewModel] = []

   ....

 }

Why might it be better to have a LocationCellViewModel array instead of a Location array in the LocationsViewModel class? Is there any advantage to doing so?

Aucun commentaire:

Enregistrer un commentaire