When do we use MVVM? - c#

I have been hearing a lot of hype about MVVM for WPF. When do we use it? Is it a use for everything or does it only have specific uses? Is it worth it for every project?

It can be useful in any project, but I find it particularly helpful in situations where providing a clear separation between business logic, interaction logic, and user interface is required (large applications or applications involving multiple developers/designers).
Model = Business Logic
Contains the model of whatever business process/object I am working with.
ViewModel = Interaction Logic
All the code that controls how the model is accessed and modified (e.g. edit/undo functionality, lazy loading, etc.)
View = User Interface
The interface (defined in XAML) that the user interacts with. I try to minimize the use of code-behind in this layer, pushing that into Attached Properties or the ViewModel.
There are doubtless many other uses for MVVM, but this particular scenario is the one I have found to be the most useful in my own WPF development experience.

I've found it useful even in relatively small projects, if I'm making a lot of use of databinding and an object data model / models.

In terms of WPF and Silverlight?
In theory for everything - every non-trivial project (and possibly even then). Its part of a wider process (it creates separation of concerns and allows for testing and other nice things). Basically if you're going to do it (and I think you probably want to, I certainly intend to with new projects) then you should do it pretty much across the board.
If you haven't already, go watch the video linked from here: http://blog.lab49.com/archives/2650 - I found it very helpful in getting my ideas straight.

Better to ask: when shouldn't you use it? The most obvious example is when data binding isn't appropriate and you have to manipulate elements of the view directly in code - if, for instance, your application needs to update the visual state of hundreds or thousands of visual elements in real time you may not be able to afford the overhead of data binding.

Every time I start on a simple project and think "this is so simple, MVVM would be overkill", approximately 8 hours later I get to a point where I realise that using MVVM would make things much simpler.
So I'd say most of the time using MVVM will actually simplify your UI logic, even if you initially think it will be overkill. Projects have a habit of getting more complex over time, and the separation of business logic and view logic enforced by MVVM enables the project to grow in a far more controlled way than having you business and UI logic all mixed in together.

I'm currently working on a large project, where we implement mvvm, CAL (Composite application guidance) in Silverlight. Of course, level of separation of concerns is very high.. but
1) the code gets too robust.
2) MVVM looks great for small projects ( all these hello-world samples all over the internet), but it reduces your oppportunities: For example, Routed events (great instrument) are still EVENTS, but, as you know, it's strictly forbidden to use them directly, as soon as this is code-behind) if you want to follow mvvm.
3) Command Binding STILL doesn work properly in Silverlight(.net4.0, vs2010). It's a long story, just keep that surprise in mind, when your CanExecute delegate will not fire at app start.
A good answer to your question is "MVVM is good for projects with simple UI logic".
Thanks, Ilya.

Related

Can the Architect be right "MVVM only splits the code behind to multiple (3) files "

I am pretty new to WPF and I have an discussion this morning with my architect who is from C,C++ background.
We are trying to create a video calling application which depends on native dlls by making PInvoke. The WPF application is mainly the UI and in code behind we are making Pinvoke Calls for Video /Audio and listing the available drivers.
So If we are talking Data as from database then there is not much of the "Data" involved in our application.
The WPF application we are trying to modify is Boghe and surprisingly they too are not using MVVM.
While I am keen on implementing MVVM the architect points it as unnecessarily splitting the files in to 3 parts.
He says if we want to change any thing in the view like changing a button or any control then it can be directly done in code behind. Why then use MVVM?
Though I have theoretical answers but can't help but agreeing to his point. Is he actually right?
He says if we want to change any thing in the view like changing a button or any control then it can be directly done in code behind. Why then use MVVM?
Of course it can be done this way. The question is whether it should be done this way.
For a fairly small code base, you can probably get away with mixing up data access, core logic, and UI manipulation in code behind. In the long run however, that will not make for maintainable or testable code, and the mess is likely to get worse over time and turn into spaghetti code. Take my word for it, because a good portion of my time at work is put into reversing such old messes.
Some consequences of mixing everything up in code-behind are:
Code that fundamentally violates the "Single Responsibility Principle" (SRP).
Code that's hard to understand because it does very different things all in the same place.
Code that breaks easily. I change something here and for some arcane reason, some feature breaks over there.
Code duplication / violation of the "Don't Repeat Yourself" (DRY) principle. You often find the same logic in several places. Is this accidental, or on purpose? If I change logic here, must the same/similar logic over there be changed too?
Note that with the exception of the first point, these are not theoretical concerns, but very real, immediate problems of your typical "legacy" code base.
In my opinion, it's not entirely correct to say that MVVM introduces more code-behind classes. This is clearly a statement from someone who does not appreciate the fundamental separation of concerns that comes when you isolate the data, business logic, and UI logical layers from one another: Even with MVVM you have only one code-behind class for your views. The other two classes (yes, there will likely be two more) simply can't be considered "code-behind" because they aren't directly tied to the view / designer.
Short Answer: No!
ViewModels are not the same as Codebehind in different files.
With a proper MVVM implementation, you do not have a codebehind, or at least
a very small one.
But in the ViewModel you do not have direct access to the window, as in MVVM
the communication between ViewModel and View is done over Binding, there is
no direct reference to a View (normally).
MVVM brings in some enormous advantages over view centric approaches.
It is testable, it is far easier changeable, it is an adapter, ...
edit
And if he really is your software architect, he should know better...
at least thats what I expected from a software architect
I too agree with stakx and Mare Infinitus; MVVM provides a lot of benefits and is not just creation of multiple code behind files.
From my experience MVVM is the best way to learn and use the power of WPF, it kind of encourages and forces you to use WPF features like Binding, Commands, Styles, Converters etc. I have seen application's being developed without MVVM and they turned out to be WPF application in Winforms style having problems stakx mentioned (and more).
Apart from UnitTesting(which I think is very imp. in your application), re-usability etc. one very important benefit of using MVVM is that it can support multiple views, i.e. you can have multiple UI's for your application all of them can use same ViewModels; This may not be a requirement for you today but you may require to have a new interface few years down the line or support other platforms like Silverlight or Metro in future, MVVM will save you a lot of effort in that case.
I would suggest you to go through this post which explains real benefits of MVVM and explains other so called benefits (although I feel they are real benefits in practice) - MVVM Backlash
one purpose is that you can unittest your view logic(viewmodel) without the view.
here one nice comment from Rachel regarding viewmodel first approach:
Remember, with MVVM your ViewModels are your application. The View is
just a pretty interface that allows users to interact with your
ViewModels.
If you have only two people in the project, and everyone's all-in-one person, he's right.
But if you do not want designers messing up the controller (or ViewModel), or programmer that changes view to something, you know, as programmers do design.
In addition, You have the clue where to do changes immediately, without searching enormous text files.
Also, the separation by MVVM or MVC is one of basic principles of programming, it's Data-Logic-View separation, and if architect says you not to do it, may be it's time to ask another architect :)

Is MVVM more necessary/important to Silverlight/WPF than MVP to Webforms?

I hope the title reflects what I'm really asking. It seems to me that when people undertake XAML based development whether to use MVVM is not even a question, rather an understood fact. Coming from a background of Winforms and Webforms, I found that we almost never used MVP (for example). It was well understood that the main reasons to go down the MVP path (other than being a purist) is higher level of unit testing, and the ability to share "view logic" with different UIs. As far as the later is concerned, it has never been a requirement in my projects. If anything we might have had several user controls for this purpose.
As far as unit testing, I never found it necessary to test my code behind because it did nothing more than handle UI events and act as a proxy (create instance of and bind) to my business layer. I can understand if people bypass the business layer and create instances of their favorite data access layer directly in the code behind, then apply business logic to it right there, where MVP would be a huge benefit. In my cause I always front the DAL with a BLL, so where is the real "win" here as far as unit testing?
Point being it was never automatic to use MVP. I am now looking at possibly using Sliverlight (for the first time) in a project and I feel like I'm going to be committing a sin if I don't use MVVM.
I know there are a slew of little things that are MVVM specific perhaps that were not a consideration before when I was making the "to MVP or not to MVP" decision. I've read about Blend support (I don't even have Blend), maybe some other important aspects? The bottom line is though, is MVVM really that much more important to Silverlight than MVP was to Webforms for example? Or are we riding the renaissance days of .NET development where patterns and best practices are taking center stage (sort of like Java).
We moved from Vb.Net winforms to C# and WPF/Silverlight under MVVM. It is definitely a change of pace from our adhock coding. I love being able to create multiple views to work with the same view model. Makes it easy to customize screens for our customers that want it without a whole lot of programming changes.
I found these posts in Stack Overflow that might answer your questions:
Benefits of MVVM over MVC
Why MVVM and what are it's core benefits?
MVVM Unique Benefits
Those have some good answers comparing MVP to MVVM.
Hope that helps.
**** Additionally **
If you were referring to Expression Blend, I used blend when I first learned xaml. Now that I know what I am doing in it, I rarely use it unless I need to do something complicated with animation or whatnot. I use visual studio for coding it since, from my experience, Blend is still cumbersome. Don't get me wrong, it's a great program and does animations great, but it's for designers, not coders really.
From my limited experience with WPF and MVVM, my opinion is this:
MVVM is a pattern, but is not the end-all-be-all of WPF. Especially in the case of MVVM "purists." There are times and places for event handlers and code behind, even in WPF. The benefit of the xaml development and MVVM is the separation of logic from design, but at times, you logic involves your design much more directly than MVVM allows.
I guess the main reason why MVVM is so advocated because of the power of DataBinding.
With web forms for example, you will need to create your own interfaces, framework etc... to implement MVP, whereas in Silverlight/WPF, databinding is just there, so whether or not you use it, it is up to you.
In my opinion, I think MVVM simply adds in a layer of testable view logic (ViewModel) instead of like the MVP pattern where your business logic can really be in the presenter itself.
In summary, if it is already there, easy to use, use it.. it is like you have a car, but u can still choose to walk 10miles to your nearest market, or you can drive (most would advocate you to drive).
Thats my 2 cents.

c# Winforms MVC

I have never used MVC before and would like some advice.
I have actually already written quite a bit of code, but looking at it, it seems to be quite highly coupled between classes and there is a lot of code written on the actual main form of the winform. I am a University student, recently started on a 12 month placement, so do not have much real world experience.
My system is effectively a WinForm GUI that has, amongst other things, a treeview that is popualted at load via an event. And then when the user clicks on a node, it gets a datagridview from a dllplugin (which obtains the data from an Oracle DB via a perl script.
My question, is would MVC apply in this circumstance, and would anybody have any good advice/resources on how I can now, post-design to implement it?
Thanks.
The MVP pattern is more adapted to WinForms applications. Here's a nice article you may take a look at.
Received wisdom is that MVC is good for the web but has some constraints when operating in a desktop environment (I'm not sufficiently experienced in applying this sort of pattern in either context to make a worthwhile judgement).
The pattern that Microsoft (for one) are pushing for forms use is MVVM - which is Model View View Model - and it provides a similar set of benefits in terms of separation and testability. Even allowing that I could wish I knew more I can see what and why, especially if you're looking at WPF (and Silverlight) but in any context where you're trying to ensure separation.
The MVC pattern can work well with WinForms, see this question.
There are lot of related pattern to choose from; in the case of WinForms (unlike WPF) there is no clear winner.
Partly this is due to everyone having different aims, do you care most about:
Code reuse between Forms in the UI
Being able to support form the one UI system
Easy unit testing
Etc

WPF Custom Control Design Patterns. MVVM?

I am creating a custom control in WPF, it is the highly unoriginal example of a stock ticker that I am deriving from the Control type. My question is: Are there any recommnded design patterns for controls themselves (as opposed to the app)? I am using MVVM for the application as a whole but just wandered if it is good or bad practice to use such a design pattern with the control itself.
My reasons for thinking of using MVVM for the control is that:
It is a relatively complex control, in that it has a graphing ability and Dependency Properties of Midprice, Average etc etc
To have a ViewMOdel as part of it would make unit testing it easier (or even possible)
Makes the entire coding process easier, especially as I have a bespoke ObservableCollection of point types.
Any thought on the matter would be brilliant. I just don't know if this is good practice or not.
Many thanks
1) Future Extensibility - Which I would say is the core when it comes to control development.
2) Good API Design - Create as much as Proof of Concepts.
3) Comes the pattern - If it is really big control. It is good to go with MVVM. But, learn to compromise it as well. Some times, we'll feel when it comes component development strict adherence to MVVM makes the control really complex.
4) Avoid over exposing of properties - Add properties as and when required. [Control feels it like an abuse, if properties are over exposed. ;)]
5) Make the control Lookless. Refer L for Lookless
General:
Try to make the control blendable from starting. It would help you to realize how good and usable from starting. Above all, it gives much satisfication and easy to track the completeness of the control.
When it comes to selecting a particular feature, think in two aspects:
1) Control's usability and
2) Control's Completeness.
If the control itself is self contained and sufficiently complex to be called a view by itself, I would go with the approach of creating a separate viewmodel for the control itself, like you suggest. Otherwise, I'd just let it live in the view that it's hosted in.

Architecture for WinForms applications?

I have started a WinForms project a few weeks ago and as I did not really know what features I wanted, I just added them along the way. This now caused a horrible mess where my MainForm is a big ball of mud and where for example some important state changes are triggered by UI elements to the point I have to call the OnChange Event of a Control in order to change some state in the database.
In short: I've just started a new project where I want to take a better approach. I just don't know which would be the "good" one. In ASP.net MVC, I found the MVVM Pattern really useful, but on the Desktop, MVVM seems to be only intended for WPF, not for WinForms.
The other approach is a three-tier-architecture: I have my Database-Class which currently talks directly to the UI. I now create a new Static Class ("ApplicationState") that talks to the database and fires events to tell the UI "Hey, Something changed!". The UI would manipulate the State which will then handle the database persistence and again raise Events if the UI needs updating. The point here is that the ApplicationState class never modifies the UI directly, but that the UI subscribes to Events. That looks like a clean/"MVC-y" way of doing it, but maybe I am overlooking something here?
Basically my ultimate goal would be to have the UI completely independent from the database layer just to make sure I don't wire in business logic into the UI again.
Don't throw in the towel on MVVM - it's valid for WinForms as well. Basically, if you use data-binding, you have to make a decision about what your objects will bind to. Often, especially for more complex UI, you dont want to bind directly to your domain objects, you want to build specialized classes (sometimes wrappers) that your UI can bind to which provide everything the view needs (the essence of MVVM) and the technique works just as well with Winforms.
A good series on WinForms Model-View-Presenter approach can be found at
The Build Your Own CAB Series Table of Contents
What I would always go for (first) is to have a layered application
Presentation Layer (JUST UI and databinding logic)
Interface Layer to the Business Layer (defining the contracts for accessing the BL)
Business Layer implementation (the actual logic, data validation etc...)
Interface Layer to the Data Access Layer (defining the contracts for accessing the DAL)
Data Access Layer implementation
This organizes your application extremely well. Then I'd look for some MVC kind approach. I did not develop so much with WinForms, more with Asp.net and some Java Desktop clients (where I used MVC). WinForms works more with the .Net databinding approach (DataSource, DataMember,...). You should go for that approach instead of trying to force something other. I found that it doesn't match that well.
What's always useful is to lay out our UI logic into different controls (like UserControls in Asp.net). This facilitates reuse.
NDepend documentation comes with some pretty cool and advanced online blog posts, articles and white books concerning architecture of .NET code.
Advices on partitioning code through .NET assemblies
Control Components Dependencies to gain Clean Architecture
Re-factoring, Re-Structuring and the cost of Levelizing
Evolutionary Design and Acyclic componentization
Layering, the Level metric and the Discourse of Method
Fighting Fabricated Complexity
Also, if you want to continuously check that your UI code is independent from your database code, you can write easily some Code Query Language rules that will be checked live at development time in Visual Studio:
Keep your code structure clean
Just start writing unit-tests for everything you can think of. As some pieces will turnout difficult to unit-test because of tight coupling to the WinForms, separate them out. Clean. Wash. Repeat.
Nido framework is good. However it is just for your back-end architecture. It will give you a solid, flexible, and simpler back-end with t4template. It prove to be having a very good architectural pattern. Furthermore it can plug not just with WinForm but with any other (MVC ASP.NET etc) front-end too..
Then again RocketFramework is also good
Link1: http://rocketframework.codeplex.com
Link2: http://nidoframework.codeplex.com
Our rule of thumb is to lean towards MVC for most websites due to the stateless nature of the web. Unless you're trying to provide a very rich web experience and bring in silverlight, then you should go with MVVM. XAML goes hand to hand with MVVM and can be your smart client choice as well (or a nice MVCP pattern).
True MVC is almost impossible to uphold in any other circumstance due to the fact that controllers are suppose to handle all input. Most non web architecture has controls that will provide this for you. In fact, most say that ASP.NET MVC is a hybrid MVC anyways but it's very good in my experience.
Okay,
I found some nice answers above but as per my 4+ years of experience in winform, I can say that you can use dotnet remoting for this purpose. In simple words, you need to create one solution for your business logic and client side works and another solution for connection with the database which you can called as a server. Both solution should contain some common projects and then you can easily works on your application without worry about your database.
I would suggest you to read about dotnet remoting.
Hope, this answer is helpful.

Categories