Mvvm in the real world tccc10

1,982 views

Published on

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,982
On SlideShare
0
From Embeds
0
Number of Embeds
48
Actions
Shares
0
Downloads
29
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide
  • http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspxWhen implemented on a class,INotifyPropertyChanged allows you to notify consumers about changes in the values of your properties by raising the PropertyChanged event. The PropertyChangedEventHandler takes the sender (instance raising the event) and PropertyChangedEventArgs (adds [string PropertyName] to the standard EventArgs) as arguments.
  • http://msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged.aspxWhen implemented on a class (almost always a collection),INotifyCollectionChanged allows it to notify consumers that the collection has changed by raising the CollectionChanged event. The event arguments specify how the collection changed (NotifyCollectionChangedAction) and the items that changed.Add – Item(s) were addedRemove – Item(s) were removedReplace – One item was exchanged for another. I.e. say x[3] = Foo; if I then say x[3] = Bar; the object (Foo) at index 3 is replaced (with Bar)Move – An objects was moved to a different index, e.g. collection was sorted, the object at index 3 was moved to index 5.Reset – A large change has happened to the collection and anything watching it should just reinitialize. Most commonly happens when the Clear() method is called.
  • http://msdn.microsoft.com/en-us/library/ms750612.aspxDataBinding allows two properties (as long as one is a DependencyProperty, discussed later) to have their values stay synced up.
  • Value converters (classes that implement IValueConverter and/or IMultiValueConverter) are used to convert values from value to another. Frequently used in data binding where the two properties have a known relationship but not necessarily the same value. For instance I might convert a booleantrue into Visibility.Visible and false into Visibility.Collapsed.
  • http://msdn.microsoft.com/en-us/library/system.windows.dependencyproperty.aspx
  • A User Control allows you to group a set of visual elements into a single unit and gives you a code behind file, allowing you to add custom dependency properties. If you are not going to have any code behind in your User Control it’s usually better to use a DataTemplate instead which basically functions as a User Control without the code behind.
  • Command Pattern = a design pattern where an object is used to represent and encapsulate all the information needed to call a method at a later timeDelegateCommand overview - http://kentb.blogspot.com/2009/04/mvvm-infrastructure-delegatecommand.html
  • Blend/Visual studio workflow is really a goal of MVVM rather than the more general Presentation Model pattern. However use of a Presentation Model pattern will tend increase the separation of designer and developer allowing them to work without stepping on each other’s toes.
  • See http://martinfowler.com/eaaDev/PresentationModel.html
  • The highlighted portions of each pattern are their “Presentation Model”, this is where the real differences in the patterns reside and is often the most difficult layer to get right.
  • The model is/should be exactly the same across all of the presentation model patterns and many other architectural patterns allowing you to share it among applications if necessary.
  • The View Model is the hardest layer to get right in MVVM. Most people when first using the pattern will try to make the View Models either be a code behind for the view or a façade/adapter for the model. Neither is correct. We go over some of the warning signs and how to shift your approach throughout the presentation.
  • The interface to the user. Shouldn’t contain much in the way of code or logic other than what’s necessary to display data.
  • Your unit tests will tell you very early if your View Model is starting to become too tightly coupled to a particular View or Model.
  • Check Wikipedia or one of a hundred blog posts for a more in-depth explanation.
  • The one thing to remember is to choose one and stick with it.
  • Most talks and blog posts about MVVM claim you should have no code in the View. That’s mostly true but there are a few times when you won’t be able to avoid it.
  • Think of it as technical debt with a low interest rate. Not to be taken on lightly, but a better choice than some other areas.
  • Use them wherever necessary but they can let others do stupid things if put into the Model so consider what people will do in the future with the extra power before putting them in the model.
  • These are the issues I’ve seen pop up the most often. If you’ve run into other general issues I’d like to hear about them. Feel free to send me an email at bryan.anderson@ilmservice.com
  • Fluffy represents both, your users who are annoyed that you popped up a message box on them, and your fellow developers annoyed that unit tests no long run unattended because they have to click OK on a message box. You’ve been warned.
  • There are many ways to display an error/warning/notification in the user interface without resorting to a message box. I personally like the way www.stackoverflow.com does it but you could also do something like a browser’s status bar or use adorners.
  • This is the page I recommended searching for http://marlongrech.wordpress.com/2008/12/13/attachedcommandbehavior-v2-aka-acb/
  • Code behind is a lot like a goto, you might not think it will cause a problem but you should check for lurking raptors first.
  • It really just comes down to logic and experience. Ask yourself if a certain portion would change if you changed the way you’re presenting the information in the view. If it would it probably belongs in the view.
  • I tend to lean toward using the command parameter more often than not because it tends to have fewer side effects and I think it presents a more consistent interface to consumers of the view model. However, many people favor an extra property because they find that it’s easier to understand what the value is and where it comes from.
  • Don’t think of MVVM as sets of M, V, and VM running around as triples. There is a many-to-many relationship among all of them even if they sometimes pretend it’s a one-to-one.The single responsibility principle comes into play here especially in the View Model, follow it and a lot of your issues will go away.
  • I’d love to hear feedback on the talk and/or these slides (both positive and negative). Please don’t hesitate to let me know what you thought.
  • Mvvm in the real world tccc10

    1. 1. or How I Learned to Stop Worrying and Love the Binding<br />Bryan Anderson<br />MVVM in the Real World<br />
    2. 2. Vocabulary<br />Presentation Model pattern<br />MVVM Architecture<br />Compare MVVM to MVC<br />Religious Fights<br />Common Issues & Solutions<br />What am I going to talk about?<br />
    3. 3. //Notifies clients that a property value has changed.<br />publicinterfaceINotifyPropertyChanged<br />{<br /> //Occurs when a property value changes.<br />eventPropertyChangedEventHandler PropertyChanged;<br />}<br />INotifyPropertyChanged<br />
    4. 4. //Notifies listeners of dynamic changes, such as when items get //added and removedor the whole list is refreshed.<br />publicinterfaceINotifyCollectionChanged<br />{<br /> //Occurs when the collection changes.<br /> eventNotifyCollectionChangedEventHandler CollectionChanged;<br />}<br />//Describes the action that caused a CollectionChangedevent.<br />publicenumNotifyCollectionChangedAction<br />{<br /> Add, Remove, Replace, Move, Reset<br />}<br />INotifyCollectionChanged<br />
    5. 5. Keeps data in two properties “bound” together<br />Allows data to flow in either or both directions<br />Uses PropertyChanged & CollectionChanged to keep values updated<br />Data Binding<br />
    6. 6. Implements IValueConverter or IMultiValueConverter<br />object Convert(object value, Type targetType, object parameter, CultureInfo culture)<br />object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)<br />Converts inputs from one value to another and back<br />Used extensively in data binding<br />Value Converter<br />
    7. 7. Looks like a standard CLR property on the class’s interface<br />Adds additional infrastructure features like<br />Data Binding<br />Change Notification<br />Value Coercion<br />Used extensively by WPF and Silverlight to create fast, reactive user interfaces<br />Dependency Property<br />
    8. 8. Groups a related set of controls<br />Reduces repetition – DRYer<br />Has its own code behind – allows new dependency properties<br />User Control<br />
    9. 9. An implementation of the Command Pattern<br />In WPF & Silverlight the ICommand interface is used to define a class that represents a command<br />bool CanExecute(object parameter)<br />void Execute(object parameter)<br />event EventHandler CanExecuteChanged<br />Frequently implemented by creating a DelegateCommand class<br />Commands<br />
    10. 10. INotifyPropertyChanged<br />INotifyCollectionChanged<br />Data Binding<br />Value Converter<br />Dependency Property<br />User Control<br />Commands<br />Questions?<br />
    11. 11. Guide the separation of concerns<br />Encapsulate what changes<br />UI<br />Web services<br />Databases<br />Anything else that interfaces with something outside the application<br />The Purpose of Architecture Patterns<br />
    12. 12. Separate presentation from functionality<br />Testability<br />Consistency<br />Maintainability<br />Allow a combined Blend/Visual Studio workflow<br />Goals of the Presentation Model<br />
    13. 13. Abstract Pattern that defines a family of platform/framework specific patterns<br />MVVM – WPF, Silverlight<br />MVC – Web<br />MVP – Winforms<br />Designed to pull the state and behavior out of the View into a more stable and testable layer<br />Presentation Model<br />View<br />Presentation Model<br />Model<br />
    14. 14. Abstract Pattern that defines a family of platform/framework specific patterns<br />MVVM – WPF, Silverlight<br />MVC – Web<br />MVP – Winforms<br />Designed to pull the state and behavior out of the View into a more stable and testable layer<br />Presentation Model<br />View<br />Presentation Model<br />Model<br />
    15. 15. MVVM Architecture – Model<br />Responsible for business logic<br />Interacts with persistent storage, e.g. database, web services, files, etc.<br />Capable of being shared among related applications <br />View<br />Unit Tests<br />View Model<br />Model<br />File System<br />Web Services<br />Database<br />
    16. 16. MVVM Architecture – View Model<br />Should be thought of as an Abstract View<br />Exposes properties and commands for use in a View<br />Gets data from the Model and updates it according to property changes and command calls<br />View<br />Unit Tests<br />View Model<br />Model<br />File System<br />Web Services<br />Database<br />
    17. 17. MVVM Architecture - View<br />Presents data to the user<br />Handles input<br />Interacts with the View Model by data binding to properties and commands<br />Should contain no logic that isn’t entirely a view concern, e.g. which screen to show<br />View<br />Unit Tests<br />View Model<br />Model<br />File System<br />Web Services<br />Database<br />
    18. 18. MVVM Architecture - Tests<br />Acts as another View<br />Interacts with the Model and View Model to ensure correct behavior<br />Provide an early warning that the architecture isn’t correct<br />If testing is difficult, coupling is too high or concerns aren’t separated<br />View<br />Unit Tests<br />View Model<br />Model<br />File System<br />Web Services<br />Database<br />
    19. 19. The Model holds data and handles business logic<br />The Controller receives input and makes changes to the View and Model accordingly<br />The View renders the Model into a form suitable for interaction<br />MVC<br />Controller<br />Model<br />View<br />
    20. 20. Religious Fights<br />
    21. 21. Multiple, mutually exclusive options<br />People form strong opinions and will argue the benefits of their choice for all eternity<br />Each side has its own benefits and drawbacks<br />A decision needs to be made before the “correct choice” can be determined<br />In the end it comes down to a combination of reason and instinct<br />Religious Fights<br />
    22. 22. View Model Driven<br />Allows more complete testing of logic to open new Views/View Models<br />Tends to be DRYer as applications grow<br />More difficult to use in Silverlight projects<br />Religious Fights – Round 1<br />View Driven<br />Easy to track which View Model is used by a View<br />Much easier to use when sharing code between WPF and Silverlight<br />Difficult or confusing for a single View to be used with multiple View Models<br />
    23. 23. How much code should I actually have in the View’s code behind?<br />Value converters are fine as long as they’re only converting values<br />User Control code behind should only contain Dependency Property definitions and rare view-specific event handlers<br />DataTemplateSelectors as long as their code is limited to choosing between DataTemplates<br />Otherwise there should be no code-behind<br />Religious Fights – Round 2<br />
    24. 24. Should the View be allowed to use/display a Model class directly or should all interactions be through the View Model?<br />The View should never edit a Model instance<br />My rule of thumb – Only allow the view to display immutable Model objects, even then try to avoid it<br />It should be considered technical debt if done, but it’s a relatively harmless area to take on debt<br />Religious Fights – Round 3<br />
    25. 25. Where should INotifyPropertyChanged and INotifyCollectionChanged be used?<br />Definitely in the View Model<br />Occasionally in the View - usually in Custom Controls and more rarely User Controls<br />It’s becoming more accepted to them in the Model unless added to push updates to a View<br />Religious Fights – Round 4<br />
    26. 26. Notifying users from a View Model, i.e. How do I show a message box?<br />How do I handle non-command events without code behind?<br />Something should or should not be shown based on state. What goes in the View vs. View Model?<br />Should I use an additional property or the command parameter to pass contextual data to a View Model’s command?<br />View Models seem to copy all of my Model’s properties<br />Common Issues & Solutions<br />
    27. 27. Message boxes are annoying<br />Notifying users from a View Model<br />
    28. 28. Message boxes are annoying<br />Messages to the user are useful<br />Use a mediator – Allows you to aggregate messages from all of your VMs, log them, and display them. Also easy to test.<br />If you only need it in one or two places an Error/Notification property or, more rarely, event works well.<br />Implement the IDataErrorInfo interface for notifications related to property validation<br />Notifying users from a View Model<br />
    29. 29. Usually done using an attached behavior, search for “Attached Command Behavior”<br />Can it be handled by binding? <br />If absolutely necessary and there’s no logic involved it can be put into code behind.<br />Handling events without code behind<br />
    30. 30. Code Behind & Gotos<br />http://xkcd.com/292<br />Beware of Raptor Attacks<br />
    31. 31. Is it a View-only concern? E.g. Master/Detail view<br />Bind the detail view to the selected master item<br />Is it a View Model concern? E.g. IsEditMode<br />Use a DataTemplateSelector if available to switch Views<br />Use Triggers, Visual State Manager, or another method to switch views based on the View Model properties<br />Is it a combination? E.g. IsBusy<br />Use the Visual State Manager if available<br />Visibility based on state, what goes in the View vs. View Model?<br />
    32. 32. Would the property be referenced anywhere outside of the command(s)?<br />Does the property make sense in the context of the View Model’s interface? <br />Is the command used in multiple places that would need to set the property to different objects?<br />Property or command parameter?<br />
    33. 33. View Models are not just Façades or Adapters for Model classes<br />View Models are not the code behind for a View<br />View Models are an Abstract View or the Model for a View <br />View Models will present multiple Models and multiple View Models might use the same Model<br />View Models just copy my Models<br />
    34. 34. I love feedback!<br />Bryan Anderson<br />bryan.anderson@ilmservice.com<br />@SolaAesir<br />Questions?<br />

    ×