What pattern is this refactoring? - c#

I have an example with a bunch of logic in my GUI class (winforms). I am going to refactor that so that there is no logic in the gui and a separate class holds all the logic.
What is that pattern? Say I had a form class called AddAddressForm, what would you call the associated file that holds the logic? AddAddressMediator (doesn't quite fit that pattern), if I was doing WPF I would call it the ViewModel (but I am not).

Sounds something like model-view-controller without the model part.

I don't think its called anything. I've tried doing that sort of thing in the past with Windows Forms, but unfortunately it didn't really work:
For each form I had another class called something like MyFormLogic that supposedly contained all of my logic for the form, with the form itself just containing a load of methods and events for manipulating the form (things like an AddButtonClicked event, and a AllItems collection property)
It seemed like a brilliant idea at the time (Yay easy unit testing!), but what actually happened is the MyFormLogic class became just as big and messy as before, and now I had a whole lot of extra pointless code exposing the extra methods events in my actual form class. (Also creating an instance of forms was a pain)
I'd recommend that instead you work on refactoring out as much logic as possible into lots of smaller classes that do 1 thing, rather than 1 extra class which deals with all forms logic (Its difficult to explain what I mean without some examples)

By the example given , it seems that your object shares some kind of common data.
Look at the Flyweight Pattern then.

I believe it is called Model-View-Presenter pattern. although it is commonly used in asp.net, it should be applied to WinForm as well.
http://msdn.microsoft.com/en-us/magazine/cc188690.aspx
Martin Fowler splits original MVP pattern into 2 patterns , Supervising Controller and Passive View, But I still like its original name , MVP.

it depends type of logic , say you have Conditonal Logic and you create different object from it , so seprating this in a new class will be pointing to Factory Method.
2- If you have complex algorithms in your class and you seprate it another class/s , you most probably using Strategy Pattern.
lot of other combinations also possible.

It's Model-View-Controller (MVC). In your example, the Model is the Address, the View is the dialog, and the Controller just mediates events from the dialog to the Address object.
Note: you may omit the Controller for really simple situations, but don't if you ever want automated unit-tests; the separation (via interfaces) will pay off.

I believe this is called Humble View.
For more details and different takes on it, see the Humble View section of the GUI Architectures page on martinfowler.com.

What you describe is still the Model-View-ViewModel pattern, which isn't specific to WPF. The core tenet is that the ViewModel contains state and logic, and the View constantly synchronizes itself with the ViewModel. This is nice and easy with WPF bindings, but they aren't a prerequisite; any stateful UI can utilize MVVM. The Forms flavor of the pattern can get quite wordy on the view side.

Sounds like your basic separation of concerns by breaking out the view and functionality into different files. Not really sure if it really falls under any sort of pattern per say, but it does remind me of web forms a liitle bit with the views and code behinds.

Related

Business Logic placement in WPF application

This might be a long list of questions but please bear with me. I started building LOB applications with WPF, PRISM, CODE FIRST and SQL CE, and after my first application (or attempt) I have many questions, so to begin with:
Where should business logic go, in the model or in a BLL layer just above the domain layer ?
Should view models receive references to repositories or should repositories be used only by the domain model objects ?
To put the second question in another way, what sort of objects should be given to view models ?
I use the same view model in display (in a data grid for example) and for editing in a form but that causes a lot of trouble, is there a better way to do this without code duplication ?
The biggest problem I have faced was that I always organized my view models in hierarchical relationships without allowing the children in the hierarchy to obtain references to their parents, and since the views bound to those children and invoked methods that caused the addition of objects to the repositories I couldn't find a way to notify the parents of the changes to the those repos. so the bound views could be updated, I have seen some people solve this using events but I don't like this solution and I would like to know if there is a better way to do it ?
Can anyone point to an example of building real life LOB applications using the technologies mentioned above, at least not examples that use VB .NET or WCF (I want local databases).
I'm developing a LOB app right now, with WPF, Entity Framework Code First and SQL CE 4.0 with a local database. I'm not using PRISM, but I'm using MEF as IoC with my own implementation.
So far, I recommend that you use the benefits of Code-First approach and implement as much business logic in your domain classes as possible. Also implement INPC in them. If you don't you'll end up having all your properties duplicated in your ViewModels, which is nonsense. There is no rule that says that the model should be dumb (although some people tend to think so), but a dumb model just makes the ViewModels more tedious to work with.
No clear recommendation here without knowing more of your project, but common sense: try to stick to best practices unless they start coming in your way. "Perfect" is often the enemy of "good".
Let the ViewModel get whatever they need (single model objects, collections, etc.) to serve your views. Often the simpler solution is easier to maintain in the long term.
I don't quite understand what you mean with this... I use my ViewModels several times if possible, but think that a ViewModel's function is to serve a View, if you are having trouble trying to get one VM to work for several Views, it's probable that you need to divide it into two different VM. Just gather all the common properties and methods in a base class and inherit from it as you need.
There are some loose-coupled ways for the VMs to communicate with each other. I'm using MVVM Light Messenger class for such things, but I understand that PRISM provides a similar functionality. It's not a sin to reference the parent from the child if you don't abuse it. I have a ViewModelBase<T> and the child have a reference for their parent pointing to the base class and specifying the T type, a good balance between hard and loose reference so far.
If someone points you to such an example, let me know! Actually, working with a local database should be simpler. In my case I'm using a singleton context (which a lot of people seem to loathe) but since this is a local app, with a single user and no threading complications a singleton context makes my life much easier. I'm still waiting to find a real good reason not to do so with this conditions.
PS: some people will probably downvote your question because... it is not ONE question, and it opens room for a lot of debate. If it gets closed, try the chat.
Hope this helps you, regards!

Managing a big WinForm code

I want to ask pro developers out there that how they manage a big windows form class. Is it a good idea to split it with partial keyword across different files? That's the thing that I was doing so far, but it creats unnecessry designer files that when you double click on them in VS, a blank winform will pop up:
So what I do, basically is group events and code logic for each related group of controls in one file.
My answer is "I don't". If you need a lot of code in one single class (in this case a form) it usually means your class is doing a lot of stuff and you need to make it less coupled. A good way to achieve this is to use a sort of MVC or MVP pattern form putting the logic in another place, and to use UserControls so you could have the different functionalities in different controls (with their controller or presenter, depending if you implement MVC or MVP). Divide and conquer.
I not consider me an expert, but once we had a similar problem with a main form that did not stop growing up.
The solution was just OOP, make unattached and reusable classes, those can be in the same namespace with internal visibility.
For Example there you have a ComparisionForm.Menu that looks that can be unattached from your main code in ComparisionForm.
From another point of view 'Readability'.- Partial classes are useful but take into account that even with that division of code in different files, the logic is not always divided, that makes the code hard to read, understand and finally hard to maintain.
Divide logically my classes for my was the solution. You know what say they "Divide and Conquer"
I think the best way to separate the code of a form, it's to use UserControl.
And in my case, when I have a big class, I use region instead of partial class.
Not a pro, but my two cents are: Don't have a large class. Extract most of the code to other classes.
You'll gain, also, that you'll be able to make most of the methods private, thus reducing Intellisense "noise".

Should UI components ever be passed to a Business Logic assembly for binding

I've recently been handed a code base which does a few things I'm a little different to how I usually do them.
The main difference is that it seems to pass elements (say for example a drop down list control) down to the business logic layer (in this case a separate project but still in the same solution) where the binding to business data takes place.
My natural approach is always to surface the information that is required up to the UI and bind there.
I'm struggling to match the first technique to any of the standard patterns but that may be down to the actual implementation less than the idea of what it is doing.
Has anyone ever encountered this type of architecture before? If so can you explain the advantages?
The solution is an ASP.Net website. Thanks.
Thanks,
I would make the case that this is a bad architecture, since the original developer tightly coupled the business logic to the presentation layer. If you wanted to switch from webforms to, say, MVC, you'd have to refactor chunks of your business layer, which shouldn't be the case!
If it's at all possible, you should consider moving away from developing the site in this fashion. In the interim, you can at least start the decoupling process by splitting the logic up a little bit further. If, say, you have a BindDropDown(DropDownList ddl) method, split the method apart, so you have a GetDropDownData() method that returns your actual business object, and BindDropDown only sets the values of the DropDownList. That way, at least, you'll be more easily able to move away from the tight coupling of the presentation layer and business layer in the future.
Of course, if the site is already designed like that (with a clear demarcation between the presentation layer, the intermediate "presentation binding" layer, and the business layer), I could see a case being made that it's acceptable. It doesn't sound like that's the case, however.
No, you should not pass UI elements to the Domain Model to bind / Populate.
Your domain model should ideally be able to be used with Windows Forms / WPF / Silverlight / ASP.NET / MVC you name it.
Now, I kinda understand the idea that your business objects should know how to store and render themselves etc it's the OO holy grail, but in practice this doesn't work well, as there often are dependencies (database middleware, UI components etc) with those functions, that you do not want in your BO assembly, it severely limits your reusablility.
Something that you can do though that gives your users the illusion of your BO knowing how to render itself is using extension classes (in a separate assembly, to contain the dependencies) something like...
public static class AddressUIExtensions
{
public static void DisplayAddress(this Address add, AddressControl control)
{
...
}
}
Then the API user can simply do
var ctrl = new AddressControl();
address.DisplayAddress(ctrl);
but you still have physical separation.
Has anyone ever encountered this type of architecture before?
If so can you explain the advantages?
The only advantage is speed of development - in the short-term; so it's well suited to simple apps, proof-of-concepts (PoC), etc.
Implementing proper abstraction usually takes time and brings complexity. Most of the time that is what you really want, but sometimes an app might be built as a simple throw-away PoC.
In such cases it isn't so much that a room full of people sit down and debate architectures for a couple of hours and arrive at the decision that binding in the BL makes sense - it's usually a "whatever-gets-it-done-fastest" call by the developers based on speed.
Granted, that simple laziness or ignorance will probably be the reason why it's used in other cases.
Your business layer should return a model - view model that the UI layer will in turn use to populate what it needs - period. There should be nothing sent to the business layer in terms of ui components - period. Its that simple and that hard and fast of a rule.

How should my model look like?

As I am further digging into MVVM and MVVM-light I recognized, that there is no MVVM-light provided base class for models.
But from my understanding, messaging and raising notifications could also happen in a model. At least in communication between models I would find that messaging would come in very handy.
So I just decided to derive my Model from ViewModelBase, even though some of the properties (like the design time ones) will be unused.
But the more I am looking at this, the more I think I have missed something. Is it considered "bad practice" to derive my Models from ViewModelBase?
And is it ok to use Messaging for Model communication?
Derive your view-model classes from whatever you like... MVVM-light offers the VieWModelBase to provide an implementation of ICleanUp - which is good for managing the life-cycle of ViewModel objects. My own choice has been to implement all scaffolding for Property Change notifications in a base class, then derive from that for model classes. About the only strong suggestions I have regarding model classes are:
Once size doesn't fit all. How you store your data may be different from how you interact with data, and ViewModel objects should be geared towards supporting interaction, not storage, and if you need to interact with the same data (Model) in two very different ways, then design two different ViewModels to support these different interactions.
Do use attributes (a la System.ComponentModel) to annotate the models. You can get a lot of your validation work done this way - and validation feedback is the responsibility of the presentation layer (View + ViewModel), not the problem domain (i.e. the Model).
Really good ViewModel classes are also usually stateless enough that they can be recycled/reused within a single user interaction, such that large data lists can be virtualized (WPF supports virtualization) to save RAM.
Remember DRY (Do Not Repeat Yourself), KISS (Keep It Simple, Stupid!) and YAGNI (You ain't gonna need it) - are the principles you should keep in mind above any academic design principles. I've litereally wasted weeks on a WPF app implementing academically perfect MVC/MVVM patterns, only to find that they detracted form the overall understandability of the finished solution. So... keep it simple! :)
I would take a look at the EventAggregator in the Composite Application Library. The answer in this post has a good description of it. Jeremy Miller's post goes into a bit more detail.

oo question - mixing controller logic and business logic

I'm not sure if I'm using "standard" terms, but this is a basic OO question I'm trying to resolve.
I'm coding a windows form. I don't want logic in the form event handler, so I just make a call to a custom object from there.
At the custom object, there are two sets of logic.
The "controller" logic, which decides what needs to get done and when.
The actual business logic that does what needs to be done (for example a control that performs a math operation and returns results, etc.).
My question is, does OO architecture allow for having both of these in a single object? Or is it recommended to split them out into a "controller" object and a "business logic" object? Is there a design pattern I should refer to for this?
For the time being, I've started down the route of combining them into one object. This object has a "start" method which contains the controller logic. This method then calls other methods of the object as needed, and ultimately returns results to the caller of the object.
What you're doing is a form of "fat controller" architecture. These days software development is trending toward thin controllers.
OO design is all about decoupling. If you internalize only one thing about OO programming, let it be that.
Check out "Domain-Driven Design Quickly." This free e-book is a condensed introduction to the concepts covered in Eric Evans' important book "Domain-Driven Design."
Getting educated in these concepts should help you to understand how to separate business logic from the controller, or service layer.
In general, you should probably have these in two different objects, but there's a qualifier on that. It may make sense, if your project is small enough and your object model is not complex enough, to have the functionality composed into one object; however, if your functionality is complex enough, it's almost certainly going to be better for you to segregate the controller and the business objects. At the very least, design the system with an eye towards separating the controller and the business objects at a later point, if you don't completely separate them now.
No, I don't put business logic in controllers. I add an intermediate service layer that's injected into controllers. Let the service do the work. Controllers are for routing requests and marshaling responses.
Putting the logic in a clean service layer is "service oriented", even if you aren't using web services or WSDL. It has the added benefit of still working if you decide to change controller/view technologies.
The answer to you design question can is as the following scenario: how would you design your application if you also had to provide a web-client for it.
Both your Windows Forms UI and you Web UI would be calling the same classes and methods. The only difference, then, would be how each populates the UI and communicates with the other layers.

Categories

Resources