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