What is the idea behind Grasp's Controller pattern?
My current interpretation is that sometimes you want to achieve something that needs to use a couple of classes but none of those classes could or has access to the information needed to do it, so you create a new class that does the job, having references to all the needed classes(this is, could be the information expert).
Is this a correct view of what Grasp's Controller is about?
Generally when googling or SO'ing controller, I just get results about MVC's (and whatnot) which are topics that I don't understand about, so I'd like answers that don't assume I know ASP.NET's MVC or something :(
Thanks
According to Wikipedia:
A Controller object is a non-user interface object responsible for receiving or handling a system event.
From Applying UML and Patterns:
What first object beyond the UI layer first receives and coordinates ("controls") a system operation?
Controllers, across the board - be it in MVC or GRASP or Patterns of EAA - are all about receiving input and responding to events.
I conceptualize it very literally: think of a video game controller.
It responds to input events - the user pressing buttons. It doesn't necessarily know what to do when you hit a button, but it at least receives the event.
Looking at the controller, one can easily figure out what the system events are - that is to say what inputs it responds to and how the user interacts with the system. On a Nintendo Controller, it's evident that system events are:
Press A
Press B
Press X
Press Y
Press ↑
Press ↓
Press →
Press ←
Press L
Press R
If we were to take all these events and build a software controller to deal with them, it would be an MVC controller: these events are all concerned with the physical controller as presented to the user - it's "view", if you will. But there's a second layer of input events for most video games, where button mashing maps on to specific system operations. For example, if you're playing as Scorpion in Mortal Kombat 2, pressing ← ← B triggers one of your special moves. In that case, the system could need different controllers which deal with these different kinds of events:
Here, the NES Button Controller is a MVC controller which would keep track of the state of UI elements - for example, remembering what buttons were pressed in what order. Depending on application state (see Application Controller - another one!) the NES Button Controller would response to certain button combinations by invoking methods on the other controllers - for example the Scorpion Controller - which are Use Case Controllers.
What's important is that by looking at the design of these controller objects, you can quickly and easily enumerate the system events they respond to.
Altogether, in the end, the MVC Controller is still a kind of GRASP Controller - as its methods tend to represent system events, which respond to user input. But there are other GRASP controllers which are not MVC controllers: Use Case controllers. A GRASP Use Case controller might respond to system events such as "user creates a new sale" while an MVC controller would respond to events like "system receives a PUT request for /sales/new" or "a java.awt.event.ActionEvent fires`".
Models contain data. Views present the data.
Views listen to models, using the Gang of Four Listener pattern.
Controllers decide what to do with the user input. Either they call methods on the models, construct new objects in the current Set of models, remove objects from the current Set of models, rewire views to different models, add views, remove views, or reconfigure views.
GRASP is just a tool to better understand software, and hopefully prevent one from making blatant mistakes in the creation of new software through good design practices. It really has nothing to do with MVC, but it can be used to better understand MVC.
The key in MVC is that the model isn't polluted with code that handles display details. That way you can isolate the "business logic" or "what the class is supposed to do" inside the model alone. Views react to changes in the model because the model emits messages to each view which has registered itself against the model (the listener pattern). The messages are often quite terse, basically the don't need to contain any data other than "the model has changed".
When the views get notified that a change has occurred in the model, the view then acquires the necessary data from the model's public interface. Once the view has the data it needs, it displays the data to the user (using whatever interface the view was meant to support). This isolates the presentation of the data to a class which will break when the view changes incompatibly, and allows modification of the view code without the model class requiring "compatibility" modifications.
The controller is responsible for knowing where the focus lies, and which model or view to update. It's the glue that puts things together, and is responsible for correct handling of input.
Related
I'm writing a flashcard program and am running into an issue I always seem to face when writing this sort of Forms program.
I'll describe the program then the issue.
In this program, one main form controls almost all of the action. Depending on the user's input and form events, different buttons/controls may become enabled or disabled, text in various boxes may be populated, etc.
For example:
Some questions might be multiple choice and others require typed input.
The user inputs their answer and clicks a button -- if they get something wrong, they have the option to override the 'wrong answer' judgement and say it was really a different, correct variant.
Statistics regarding which questions were answered correctly are kept and used in the decision about what flash cards to show next.
Now the issue.
How do I best create a clean interaction between the "form" code (for example, handling the OK button's onclick command, and enabling or disabling various controls) and the "logic" code (underlying data stores, program logic that does not have immediate implications for display)? If it is all mixed together in the form object code it does not seem right.
Can anyone suggest a design pattern (especially one widely used) that manages this cleanly?
In case it is relevant I am thinking of something like this:
Object Model:
Class MyForm: the form itself.
Class FormController:
Child class of MyForm.
Instantiation requires an object of type MyForm.
FormController's job is to put its MyForm object into a particular "state," by enabling/disabling controls, displaying various text, etc.
FormController exposes a small set of public functions which deal with semantically high-level request for the form state (such as "DisplayNewQuestion(QuestionData d)")
Class Session: Contains all underlying persistent data or objects involving this session, including lists of possible questions, objects that select the next question from the list, etc.
Class Driver: Drives both the Session and FormController objects. For example, it would ask the Session object for a new question, and pass it to the FormController object to update the form.
The advantage to something like this is that icky form code and nice logic code are now completely separable. But is it worthwhile? Are there better or more common design patterns for this?
Thanks a ton!
I am always most comfortable with Model View Controller in this situation. The Shade Tree Developer wrote the most informed series I have ever read on the subject, see here
The jist of MVC is
Model contains the data to be displayed
View is your form and only has logic for displaying and informing of user interactions
Controller contains the glue to make it all happen, including the business logic.
The depenencies should be
Model doesnt know about the view or the controller
View knows about the model and knows how to extract data from it to display
Controller knows about the Model and the view, instansiates them both and wires them together.
The model raises an event when it changes, the view captures this event and refreshes its display accordingly.
The view raises an event when a user interaction occurs, the controller captures this event and performs the correct action for the interaction whether that be updating the model or saving or clearing or whatever.
The view should not write to the model itself
You will see a lot of code where the form creates the controller but imo this is wrong. It came about because of people trying to apply this pattern in asp.net webforms where you have no control over the lifecycle, the first thing that always got created was a view so you had no choice but to have this create your controller, however in winforms you are in control, so make it clean, have the controller create the view.
You might want to use the Model-View-Controller (MVC) design pattern, in which the "logic" is your controller and the "view" is your UI. The model is used to access and retrieve data from your data source (a SQL database for instance)
It is worthwhile to separate your logic from your UI, because it makes them more maintainable. For example, if you want to change your UI from a winform to a web page, you don't have to redo all your logic.
Also, it makes up for a really cleaner code. Using design patterns in general helps other programmers understand your code faster as well.
when we search Google for difference between MVC and MVP then thousand of article is available but i read few but they are not showing difference in terms of coding sample. so if anyone knows any url from where i can see a sample code for both MVC & MVP implementation then please tell me the url. i want basically small sample code by which shown the difference through coding flow in c#. i hope i am very much clear what i am looking for.....i need code same code one with mvc coding flow and another with MVP. i am not asking for theoretical explanation.
I also don't have sample code on my blog post "MVVM vs MVP vs MVC: The differences explained" but I do have a section for each architecture that discusses how to implement them using words. I will describe it here.
MVP requires a few implementation details
Each view must implement an interface for the view (eg IUserEditView for editing users). This interface contains functions for things that the presenter might need to do (eg, showUsers(IList users), displayMessage(String errorMsg)
A presenter is created for each view. It contains functions that the view will need to call (eg, saveNewUser(User user), selectedUserChanged(User user))
An instance of the presenter is created in the view's codebehind. When view events occur, appropriate messages are forwarded to the the instance of the presenter. eg, when the save button is clicked, all the user details are forwarded to the presenter in the form of a new user....myPresenter.saveNewUser(new User(txtUserName.text, txtPassword.text))
When the instance of the presenter is created in (3), the view is passed as an argument to the constructor. This way, the presenter can reference the IUserEditView from (1)
That is the meat of MVP. You will probably need to implement the mediator pattern and have all the presenters inherit from base presenter. This way, presenters can send messages to each other without having to reference each other explicitly which is important (eg, if a new user is added, maybe you need to update a related view like users online).
MVC is a bit more tricky.
The controllers have a method of selecting which view is displayed. This could be referencing just a dictionary of instances of all the views but a better way is to have some class outside the controller manage the details and then the controller can just select the view with something like ShowView("UsersView", listOfUsers). Note the separate class can be a base class, or a factory, helper
A method of forwarding actions from the views to appropriate controllers. With the web, you just can determine the controller & method from the request url (eg, http://www.mysite.com/mycontroller/method, www.mysite.com/Users/AddNew/). For other systems, you will have to implement a class to manage the messages, or just directly forward them to an instance of the controller in the view. I've only used MVC with the web so I'm not so sure about the last point.
Because of (2), the view is now able to trigger actions in the controller. When it does so, the controller modifies the model (the implementation of this will depend on the details of your model).
Updates to the model get sent to the view (usually via an observer pattern). Check out INotifyPropertyChanged if using .net
Word of caution: Although I have described how to implement both methods, they should not really be considered interchangeable. There are cases when you want MVC, MVP, and MVVM. I think if you don't have technology limitations around using MVVM, then it is your best choice. I am biased but I think maybe people are moving away from MVC and towards MVVM (or MVP) except for very specific cases like ASP.NET MVC. My article describes this in more detail if you need clarification.
Short summary for when to use each in terms of C#
WinForms -> MVP
WPF -> MVVM
ASP -> MVC (if you can't use ASP.NET
MVC, then MVP will work too)
I writing an MVC app and I'm really struggling to keep my controllers lean and limit the number of actions.
For example, here is a look at my ReportController actions:
OpenCall
ClosedCall
ServiceLevelAgreement
Barrier
Resolution
Repair
Failure
Inventory
CustomerLocation
These are all my different reports. Should I be making a controller for each one?
Here is a look at my ServiceCallController actions:
New
Create
Reopen
UpdateETA
UpdateOnsite
UpdateServiceTimes
UpdateEnroute
Close
Cancel
Reassign
Show
ModifyAfterClose
This are all different actions I need to take based on what the user wants to do. Can anyone help me out here with how to clean this up?
I think it's clean already. If an object of yours is capable of doing 7-8 actions, then your structure is the way to go. If you had one controller that is responsible for the actions of multiple business objects, then I'd have suggested you change it into the way your current design is in.
One thing though about your current design, it'd be a good idea to just have one update action on ServiceCallController and that action could take what to update as a parameter. After all, all those update actions do one thing : update your business object.
But if you are still not satisfied, then you can just have one action that's named "do" which takes the action as parameter and passes that to a service layer which returns what the request wanted. But IMO, that wouldn't be a good design, so I definitely don't suggest it.
If the file it self is getting to large to work with you could either use partial classes, Or back the logic off in to a separate class and leave your controller think and lean.
So I am creating a C#/Winforms application in a model-view-controller pattern. My view-controller needs to instantiate multiple groups of objects. The object groups are elements of the model and elements of the view. So for example a textbox and the model to go behind that text box.
I'm wondering if the best way to do this is to put everything in some sort of collection and tie them together with a key?
In the WinForm MVC apps I've built, I typically don't allow the controller to instantiate anything (I try and keep the "new" keyword out of my controllers).
If I need an object I ask a service for it, and internally that service is going to fetch that object from a data source (repository or the like), or in the case of a new object it will likely utilize some kind of factory to get me a new object (with any necessary pre-filled properties already set to default values, rules run, etc.).
The way I like to think about this sort of problem is this: how would I make this work (and make it reusable) if I didn't have a GUI for a view, but instead had a command-line input for my view? The logic to create/add/delete/update the model should be somewhere in your domain, not in the controller. Then the controller just becomes the mediator between the model and the view. The view becomes an I/O mechanism that is just a prettier version of a command-line interface.
Hope that makes sense.
Have you considered using WPF instead of WinForms? It has a nicer MVC-like model and built-in databinding that is much more powerful. It would probably solve your problem and help you build with more modern technology besides.
Perhaps you should design your model to match what the view needs? Then there would be only one model for the controller to pass on to the view.
I am primary a web developer but I do have a very good understanding of C++ and C#. However, recently I have writing a GUI application and I have started to get lost in how to handle the relationship between my controller and view logic. In PHP it was very easy - and I could write my own MVC pattern with my eyes closed - mainly because of how PHP is stateless and you regenerate the entire form per request. But in application programming languages I get lost very quickly.
My question is: how would I separate my controller from view? Should the view attach to events from the controller - or should the view implement an interface that the controller interacts with?
If I was you I would expose events from an interface of your view. This would allow you to make the controller central to the entire interaction.
The controller would load first and instantiate the view, I would use dependency injection so that you don't create a dependency on the view itself but only on the interface.
The controller would access the model and load data into the view.
The controller would bind to events defined on the view interface.
The controller would then handle saving of data back to the model via an event.
If you wanted to you could also use an event broker which would void the need to declare an interface per view. This way you could bind to events through attributes.
This would leave you with the Controller being dependent on the model and the view interface, the view being dependent on the data only and the model having no dependencies.
Some examples of the above design thinking can be found in CAB and the Smart Client Software Factory Link To Smart Client. They use the MVP pattern but it could equally easily be applied to the MVC pattern.
Most every GUI framework (from MFC to SWT to whatever) is already MVC based. In fact, the MVC pattern was first created by Smalltalk-80 and later first really used for GUI development.
Double check and look at the standards and suggested practices for your GUI toolkit of choice. Sometimes MVC won't be a good pattern to work with when solving a certain problem or working with a particular toolkit.
Remember: MVC is a great pattern but isn't a one size fits all solution, don't try and force a problem into MVC when event-based or functional style programming will make your life easier.
Imagine this GUI:
The Zergling unit is presented to the user as an alien icon. You can see that it is in its idle animation. Call this the View.
The player moves the unit by clicking on it and a target location. You can subtitute the player for an AI if you want. Call this the Controller.
The HP and attack range of the unit is calculated every game frame when the unit is in combat. You can change this data to make the Zergling into a range unit. Call this the Model.
Keep this analogy in mind and extend it for your MVC designs.
The imortant thing for you to remember, is that in your MVC setup the Controller must know which View to call, but the View must know nothing of the Controller.
So your View must provide a generalized way for Controllers to interact with it, so that you can have several different Controllers call the same View (a standardized graphical output of some data provided as parameter, for example).
This gives you flexibility:
If your customer wants PDF output of
something you only provide HTML
output for, you can get away with
writing a new PDF View to be called
from the Controller with the same
parameters as the HTML View.
If your customer wants similar HTML output of a different data source (say), you can get away with coding a new Controller that provides a different data set to the same old HTML View, which gives the same HTML report just with other data.
If you keep your View detached from specific Controllers, and put the knowledge about which View to call from your Controller, you're well on your way.
Your controller should definately bind to events defined on an interface the view implements.
How you go about doing this can be the tricky part. Dependency injection? A view factory? Have the view instantiate the controller it wants? It really depends on how complex the application is going to be.
For something really quick and simple I would start with having each view construct it's controller and then look at other options if it needed to get bigger. Personally I think a full dependency injection framework is overkill for half a dozen forms :]