Are current MVVM view model practices a violation of the Single Responsibility Principle?

后端 未结 4 1011
天涯浪人
天涯浪人 2021-02-01 20:02

With current practices (at least with WPF and Silverlight) we see views bound via command bindings in the view model or we at least see view events handled in view models. This

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-01 20:49

    I consider many of the current practices around MVVM violate SPR (at least). This is yet another situation where simply adding controllers back to MVVM would solve all the problems cleanly. I call it MVCVM :)

    The pattern we are using successfully on all recent projects is to register controllers only, in modules, and initialise them at startup. The controllers are very light/slim and the only thing that needs to hang around for the life of the app listening for, or sending, messages. In their initialise methods they then register anything they need to own (views and viewmodels etc). This lightweight logic-only-in-memory pattern makes for slimmer apps too (e.g. better for WP7).

    The problem with just using VMs, as you have found, is that eventually you hit cases where they need to know about views, or commands, or other stuff no self-respecting ViewModel should be involved with!

    The basic rules we follow are:

    • Controllers make decisions based on events
    • Controllers fetch data and place it in appropriate View Model properties
    • Controllers set ICommand properties of View Models to intercept events
    • Controllers make views appear (if not implied elsewhere)
    • View Models are "dumb". The hold data for binding and nothing else
    • Views know they display a certain shape of data, but have no idea where it comes from

    The last two points are the ones you should never break or separation of concerns goes out the window.

    Simply adding controllers back into the MVVM mix seems to solve all the problems we have found. MVVM is a good thing, but why did they not include controllers? (but this is of course just my opinion) :)

提交回复
热议问题