9

I hope this is the right place to ask.

I'm an experienced developer, and have used MVC for much time. This question is in the context of iOS/macOS development for the most part, (SwiftUI).

Using MVC in iOS I always found the paradigm and architecture simple.

  • Views contained view related code (layout and reactive code)
  • Models were just stores
  • Controllers populated models, did all the business/app logic, held references to the the objects that did work (network handlers, data parsers, business logic)

In MVVM, (used in SwiftUI) I'm really struggling with where to put this code.

I see the right approach as:

  • Models are still stores they are dumb and get populated by the ViewModel
  • Views are pure in terms of their purpose, UI code only, declarative
  • ViewModels (I think) hold the logic, have references to objects that do the work, get results from these objects and populate the model, let the view know when things change.

Do I have this right, if not, where does the "controller code" go in MVVM?

Woodstock
  • 201

1 Answers1

12

In MVVM, the business logic is built into the Model. The ViewModel is there to bridge between the View and the Model, so it's logic only pertains to driving the display and updating the model from user interactions with the View.

I think the disconnect you are having is trying to have an anemic model work for MVVM, and it can't. By anemic model, I mean one that only holds data and has no logic. Even with MVC, the controller was only ever supposed to call the methods in the model layer. So your first point of what you think is right, does not in fact match the pattern.

The right approach is:

  • Models are rich: containing data and business logic
  • Views are strictly for drawing the UI
  • ViewModels hold the logic to bridge the gap from the View to the Model

Now, how you build out your model can make use of services and dumb data objects, but you should have a consistent API. Domain Driven Design helps put some structure to the concept. For example, it's not uncommon to have Repositories and such to retrieve Models and update them.

To drive this home, if you have a Button in your View, it will be bound to a Command, which in turn is invoked in the ViewModel. The Command then in turn calls a method on your Model, like Save(), or if there are parameters will collect the values from the ViewModel before calling the method.