Maybe Call Your UI Configurion Objects ViewData Instead of ViewModel

Joe Fabsevich (@mergesort) proposes to call data to configure UI elements “View Data” and keep the objects dumb.

From part 1:

In my experience, things become harder to maintain when they start becoming a crutch, as a place to put your code if it doesn’t neatly fall into the Model, View, or Controller label.

With this in mind, I realized we need an answer for configuring our views in a way that’s maintainable, and ultimately transforms one or multiple models into a view.

Joe writes that it’s futile to look for a “view model” definition (in the MVVM pattern sense) because there are so many; and that in most cases you don’t need a pattern where the view model exposes behavior to control view components anyway. Simple configuration objects often suffice.

It’s often enough to lump together related configuration properties into what he calls ViewData.

Views then expose a configure(viewData:) method. You pass in the data, the UI component updates itself accordingly.

Read Joe’s articles here:

  • Part 1: general set up, relationship between ViewData and UI components.
  • Part 2: how to map complex state to different complex UI data, and handle user interactions.

I think the view component itself is best place to put this stuff, too. It’s the view’s responsibility to display something. So give it a configure method and let it do its job!

If you follow online tutorials, you often end up with the view controller reaching into the view’s boundary to set its properties. That’s contrary to common OOP heuristics which have proven to be useful in a lot of cases (read: not 100% of the time, but often, so apply with caution) – like the “[Single Responsibility Principle](https://christiantietze.de/posts/tags/srp” which is violated if the controller also has the responsibility to do all the view’s work for them, and the general idea of treating objects as self-contained black boxes. People also speak of “train wrecks” when there are objects.reaching.into.objects.a.lot.

I’m still a fan of also using the term “view model” for this purpose, as in “a model of the view”, but if you get confused by the overloaded pattern name, then I guess ViewData is just as fine.

You can also call it a “parameter object” or “argument object” because it lumps together all the necessary configuration parameters of a view component’s configure method, and not much more. The cohesion of the view data object may be solely determined by the requirements of the view component – which may be arbitrary, but a necessary evil for display purposes. This doesn’t qualify as a “model” in a traditional sense that I can think of.