Refactoring Windows Forms Application - winforms

I am developing a windows forms application. It was basically evovled with a mix of BDUP and prototyping.
I have about 1500 lines of code (excluding IDE generated partial class... 1465 to be exact) in the form and the form has 6 tabs (9 subtabs). Does not have more than 10 controls in each form so multiple form solution would be an overkill.
I have a set of entity classes that when serialized give me an XML representation that I store in an XML file. I've encapsulated this with a Repository pattern so I could move the storage to a database in future. The form uses the entity classes (for save/edit) and the Repo factory (add, retrieve and save).
Now, my problem is that much of the 1500 lines of code deals with interaction between UI elements (making a choice in a Combo disables some elements, or displays different items in a grid, handle tab transitions (next/back buttons), loading menus (each distinct item in the xml file repository becomes a menu item), new/edit mode etc (I've three distinct sets of new/edit on the same form).
What would be best approach here to move the element interaction out? Let's say, I may decide to make it web-based UI in future.
More importantly what are the composite refactorings I can apply?
What patterns I should refactor to / towards?
Thanks for helping out.
Note: I'm reading Refactoring to Patterns... Specifically I wanted to have a "howto"/tips on Refactoring to MVC...

Martin Fowler describes different UI architectural patterns in this article. It's fairly long, but well worth reading. You will then be able to determine which patterns and architectural models fit your scenario the best.
At the end of the "Model View Controller" section of that article, Fowler mentions these items, which seem applicable for you:
Make a strong separation between presentation (view & controller) and domain (model) - Separated Presentation.
Divide GUI widgets into a controller (for reacting to user stimulus) and view (for displaying the state of the model). Controller and view should (mostly) not communicate directly but through the model.
Have views (and controllers) observe the model to allow multiple widgets to update without needed to communicate directly - Observer Synchronization.
See the article and its links for more information. Good luck!

You should look into the Model-View-Controller (MVC) design pattern to abstract your business logic from your display logic.
There is also another flavor of the same thing called the Model View Presenter.
Both of these are extensively documented on the net.
Regards,
Joon

Related

Qooxdoo Desktop Design Best Practice

I would like to know how you are Design your Qooxdoo Code.
I don't get the right Architecture which I am satisfied with.
It is hard to encapsulate the View with logic like services.
I hope someone can give me a hint to a Pattern or something to find a good solution.
One of Qooxdoo's greatest features is a strong OO class system, so really the pattern that you use is up to you - MVC, MVVC, etc are all possible because Qooxdoo's OO system provides you the tools to implement your preferred pattern(s).
One pattern that I find very useful, especially in creating larger apps, is to define custom widgets for editing models; for example, if you have models (aka "Business Objects" etc) for Customer, Invoice, InvoiceLine, and Address having a widget for CustomerEditor, InvoiceEditor, InvoiceLineEditor, etc is really useful firstly because it encapsulates the code, but also because it supports binding.
Binding is a very powerful feature of Qooxdoo - to see why, let's assume for a moment that each one of your Editor widgets has a property called value which is the thing being edited.
In simple binding, your editor can bind properties of the model to the widgets which display and edit those properties, eg CustomerEditor bind value.firstName and value.lastName to a couple of qx.ui.form.TextField and automatically changes to the customer's firstName or lastName will be updated in the two TextField's. Binding can work the other way around too, so that changes to the TextField are copied back into the model.
There is a controller class called qx.data.controller.Form that can simplify making this happen, and optionally incorporate validation of user values and user feedback too.
If you have separate Editor widgets, you can also bind to them - for example, Customer could bind value.address to an instance of AddressEditor, and InvoiceEditor could bind the currently selected InvoiceLine to InvoiceLineEditor etc

JavaScript - Interactive diagrams in Backbone.js application

Background: I'm currently developing the client side for a web application, using JavaScript, with jQuery and Backbone.js (these are required by the proponent).
This is an application to visualize and edit data, in a graphical mode (through interactive diagrams representing the data, mainly).
Terminology: Said data is under the format of multiple documents, each containing a list of items.
For the purpose of this question, let the items be composed by an identifier, a textual description, and links to items in other documents. Links should be symmetric (i1 -> i2 exists if and only if i2 -> i1 also exists).
The Current Goal: In this phase, the application should be able to read two documents, display both lists side by side, and then draw lines, connecting the items between both documents, according to their links.
These lines should be editable. In other words, the user should be able to create new links, or remove existing ones (reflecting the changes on the item models).
These documents can be somewhat long, say, some dozens of items (maybe a few hundreds, in a realistic scenario). Of course, the page will be scrollable, to allow the user to see everything.
Also, for user convenience, there should be a slider to scale the view (allowing zoom in/out effects, so the user is given a global and a local view, being the latter more adequate for editing and the former for analysis).
Furthermore, the user should be allowed to hide particular items (useful when an item has many links, creating visual rubbish).
What I've managed to do:
Read data and map it to Backbone models and collections;
Display both documents side by side (Backbone views), with item connections;
Allow interactivity on these connections (drag-and-drop to create lines, click to remove), reflecting changes on Backbone models;
Hide particular items;
Scale effects.
I've achieved this using SVG, after coming across jsPlumb.
The Problem at Hands: The application still needs adjustments (emphasis on the scaling effects). Regardless, I found jsPlumb to be comfortable to work with. However, rendering performance seems to be a little lacking, when using the slider (it's possible that the slider steps are too small, thus firing too many events).
The proponent suggested that I try, instead, Sankey diagrams, to represent this kind of data. They also suggested that I try Sankey by tamc, based on Raphaël.js.
Of course, the visual factor is also contributive.
My question(s): Does this library have a good compatibility with Backbone? Possibly, if I use the resulting SVG elements as Backbone views' elements.
Also, does any of the two have a significant rendering performance advantage over the other?
On a final note, are there any other libraries more adequate to this scenario, worth the time of rewritting the application, that I might suggest to the proponents?
The project is going on, and I ended up using Sankey by tamc, with some extra work of my own, to better adapt it to this particular case.

Where should I draw the line between view and controller in a stateful application?

In a MVC application that lives on the web, it's easy to draw the line between view and controller - views display data to the user, while controllers gather input and route the user to views based on the input provided. But in a stateful (e.g. desktop) application, it's a bit harder to know where to draw the line, because the boundaries between operations are not as clear-cut as with a web application. So where do I draw the line?
For instance, I have a view in my application that lets the user place items on a grid. Right now I have the "place item on grid" code within the view itself (accessing the grid model to do the actual placement). But I could also put it in a controller, and pass the necessary information from the view to the controller. Neither seems like a clear-cut choice - putting the code in the view will eventually bloat the view, since there will be a large number of operations that the user can do, not just place items; but putting it in a controller just seems like an extra level of indirection, making the code harder to follow.
Or am I going about this all wrong? This is a WinForms app; my "view" is actually a form, and forms by their nature can both receive input and display information. So is the distinction meaningless? Or should I have the view be separate from the form? Or is the MVC pattern incompatible with WinForms altogether?
MVC is a separation of concerns. It is designed to help the programmer keep details of the two areas separate. The MODEL and VIEW are collections/groupings of objects.
Each object within the VIEW may be part of the class sets BUTTON, WINDOW, TEXTAREA etc.
Each object within the MODEL will have a type corresponding to your domain such as CUSTOMER_DETAILS, ADDRESS, POSTCODE etc
The CONTROLLER object provides an interface into your MODEL objects, which your VIEW objects will use to communicate to your system. The CONTROLLER may also contain functionality that can not possibly be stored in your MODEL objects.
Traditional MVC also allows the VIEW objects to bypass the CONTROLLER and talk directly to MODEL objects, but is not recommended.
All objects conform to OO principles, and are complete and fully functional objects.

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

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 appears to be a violation of SRP because the view model doesn't just model the view state, but responds to the view (user). Others have asked how to build view models without violating SRP or asked whether their implementations do so (this last is the controller in MVC, but roughly analogous).
So are current practices a violation of SRP? Or is "view model" really a collection of things that don't violate SRP? To frame this a bit, it seems we need to know what is the single responsibility or if there are multiple responsibilities in the concept, are the individual responsibilities split out, conforming to SRP. I'm not sure.
Wikipedia's definition of view model says
[T]he ViewModel is a “Model of the View” meaning it is an abstraction of the View that also serves in data binding between the View and the Model
This seems good enough for SRP, but then the entry later says (my emphasis added)
[The ViewModel] acts as a data binder/converter that changes Model information into View information and passes commands from the View into the Model
In a Prism blog post about the view model's role, the author says (again, my emphasis)
What it boils down is that the view model is a composite of the following:
an abstraction of the view
commands
value converters
view state
I'm sure I've missed many definitions out there, but they seem to fall into these categories:
Single "vague" responsibility of modeling view state (so what do we
mean by state)
Multiple responsibilities (view state, user interaction (i.e.
commands))
A composite of single specific responsibilities (abstraction,
state, interaction, conversion), thus having a single
responsibility: "managing all that stuff".
If you're curious, I "care" about this because (2) feels right, but seems counter to the prevailing implementations.
Single Responsibility as Martin defines it:
"THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A CLASS TO CHANGE."
A ViewModel, as far as MVVM is concerned is really just a specialized implementation of a Presentation Model.
So while it could be argued that a Presentation Model should only represent the state of the UI, and that a Presenter/Controller should always broker the commands between the UI and the Presentation Model. If one follows this idea, with SRP dividing on State and Commands, then adding a command should not affect the class that represents state. Therefore MVVM would break SRP.
However...
I think this is grasping at straws. MVVM is a fairly specialized implementation used basically in WPF/Silverlight (and now browser clients).
Patterns are designed to make designs simpler where the alternative would be more cumbersome or less maintainable. Since MVVM is designed to take advantage of the extremely rich data binding capabilities of the presentation technologies, then it is a worthwhile trade off.
No! MVVM does not violate SRP, (the programmer does, lol!)
There is no reason that using the MVVM pattern needs to ignore the SRP. MVVM does not mean that there is only one Model Class, one View-Model Class, and one View Class. Certainly, if you only had one View Class, you could only ever show one simple screen.
Those classes that are in the View tier, should be responsible for one thing; doing, deciding, or containing. A View can consist of several sub-views who's jobs are to do certain pieces of the users interractions. Consider a basic form, it has a display grid, items in the grid can be edited, and there is a "Save" button.
The main View would be a container for two other views; the datagrid (a user control, or something) and a command control. The datagrid then is responsible for choosing the right childview to render data in; in essense it's a container that databinds. The View to edit items is a child view of the datagrid, which is in-turn a child of the main View. Lastly the command control is a set of buttons (in this case a single one) who's single responsibility is to raise signals that commands have been issued by the user.
In this way the Edit View (used by the DataGrid) is agnostic about what uses it, and has one responsibility; Same with the command control. Likewise the DataGrid doesn't care about who uses it, only that it can contain the Edit View (child). Nice SRP there.
ViewModels to match the Views (and children) are also responsible for one thing. The Edit View Model is a container to which the Edit View Binds; it simply contains the data fields that can be displayed/edited. It doesn't care about anything but signalling when one of its properties change. The Command Button View Model is a class that does things. It's commands are bound to the buttons, and it will do work based on what the user clicks on. It will have to have access to other parts of the ViewModel(s) to do it's work.
The main page View Model is there to contain the other child views. It's sole responsibility is as an initializer, making all the required ViewModel instances, and passing constructor parameters to other ViewModel instances (say, the Command Button View Model so it knows where to get data for it's work)
It's natural to cram a whole bunch of functionality into a single ViewModel that a large View would bind to. But it doesn't have to be that way, and SRP can be maintained in MVVM.
The main goal of MVVM is to allow for testable design, the Model layer can be tested independantly, all classes in the Model can easily follow SRP. The ViewModel can be tested without the need of a view; it gets trickier to think SRP in the ViewModel, but it is certainly doable; just remember to break out your classes so they only have one concern. The View is bound to parter ViewModels, with any luck, your testing of the ViewModel makes snapping the View(s) on super easy. Remember you can have each View-let adhere to SRP to be part of a larger conglomerate View (container).
TL;DR?
To answer your question directly, the View is a collection of classes that does not break the SRP. Thus, when the ViewModel is abstracted from the View(s) (View-First), they are also a collection of classes that adhere to good SRP.
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) :)
What it boils down is that the view model is a composite of the following:
an abstraction of the view
commands
value converters
view state
I don't see why you've separated the first two items. Commands are part of the view.
As for the rest - you're right. In some cases. I've built applications where the tasks of value conversion and maintaining view state were sufficiently complex that it didn't make sense for a single view model class to do it all, and I broke them out into separate classes that interoperate with the VMs.
So?

VB WPF MVC (Model + View + ?)

I have an old VB6 application. I want to recreate it in VB.Net using WPF. But I am a bit confused about the "Model View Controller"-pattern. I have two books about design patterns (GoF and J.Bishop) afair this pattern is indeed not mentioned inside one of the two books. I have also searched the internet I found some java-examples. But I have still no clue how I should use MVC-Pattern (should I?) in my new WPF-application.
Let's say for example my model (in fact it is more complex) is only a wheel rim (circle) with the properties Manufacturer, Diameter and Depth. The user should be able to modify the properties using textboxes and ComboBoxes.
Could somebody create a small example that explaines the MVC-Pattern with WPF?
Of course I like reusable classes to have a feasible concept throughout the whole application.
thanks in advance
Oops
Here's a "brief" description of what the MVC pattern is and how I would apply it to a WPF application.
(I might have a few details slightly off since I've mainy hacked in Silverlight but the concept is similar enough.)
Basically, the idea is to separate concerns and define interfaces between the different parts of an application, with the goal of keeping the code structured and maintainable.
The Model in your example would be pretty much exactly as you described the wheel rim - a WheelRim class with the various properties defined in suitable data types. I would put the model i an separate assembly to keep it apart from the other code, but you can settle for just keeping the model classes in a "Models" folder. The model would also have a "twin" in a database, the model classes being pretty much one-to-one-mapped to tables.
(You might wanna have a look at Linq2SQL or Entity Framework, if the database is defined you can pretty much get the model for free along with suitable database access code.)
The View would be the actual WPF xaml files - Defining the Grid or Canvas or what have you. On the WheelRimView there would be labels and textboxes for displaying or accessing the different properties, perhaps along with product images and the like. The code behind for the view would have all the relevant event handlers (start, button_click and so on) for getting the data from the fields and passing them to the controllers.
The Controller would be any "handler code" that you would use to manipulate the data. We're talking the basic CRUD operations here, along with validation and the like. Also, the controller layer would be responsible for compiling the data in a format that can go seamlessly into the View. The WheelRimController hence would have methods like "GetWheelRimList", "GetWheelRim", "AddWheelRim", "ModifyWheelRim" and "DeleteWheelRim". The methods take the values as in parameters and manipulate the model objects accordingliy. the
I would recommend keeping the code-behind of the xaml files free from any "controller"-ish code like validation, aggregation and the like - the code behind should basically only take the values from the textboxes, listboxes and such and send them on "as is" to the controller methods for processing. Also, you should keep any data formatting code to a minimum when getting data for presentation (i.e., no filtering or translating in the view).
A typical use case of "User opens a wheel rim and edits the diameter" would play out thus in code:
User clicks "Edit" on a list page. The WheelRimView page loads.
The WheelRimView.Load() method (or corresponding) calls WheelRimController.GetWheelRim(wheelRimId).
WheelRimController.GetWheelRim(wheelRimId) gets the corresonding data from a database table and populates the properties of a WheelRim object, which is returned to the WheelRimView.
The WheelRimView inserts the property values into the labels and textboxes.
The user changes the diameter value and clicks the "Save button.
The WheelRimView.Save() method calls the WheelRimController.ModifyWheelRimDiameter(wheelRimId, diameter) method.
The WheelRimController.ModifyWheelRimDiameter(wheelRimId, diameter) method parses the diameter (if it is a string) and loads the model object. It applies the modified value to the model object and saves it into the database.
The WheelRimController.ModifyWheelRimDiameter(wheelRimId, diameter) returns a status code to the WheelRimView (for instance a predefined numeric stating any validation errors) to report the success of the save.
The WheelRimView displays a result message (hopfully "saved") to the user.
I hope that clears a few bits up.
Bevcause of the rich binding support available, WPF (and Silverlight) are well suited to MVVM (Model-View-ViewModel). MVVM is an extension of MVC that uses a view model to bind the current state of a view, instead of manipulating the view directly.
There are a bunch of MVVM frameworks available, as well as Microsoft's own Prism framework (which is arguably more useful if you have a larger, modular application).
WPF is probably more well suited to MVVM (Model-View-ViewModel). I'd recommend reading this MSDN article on MVVM and, perhaps, following their advice. There's also a nice collection of links I found on the Bryant Likes blog.

Resources