Your SlideShare is downloading. ×
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Melbourne Patterns Group MVC Discussion 2007 08 01
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Melbourne Patterns Group MVC Discussion 2007 08 01

5,000

Published on

Melbourne Patterns Group MVC

Melbourne Patterns Group MVC

Published in: Business, Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
5,000
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
82
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Intro to Melbourne Design Patterns User Group Discussion on 1-Aug-2007 On quot;MVCquot; (whatever it is! ;) by O.K. My original motivation to have a discussion on MVC was to attempt to use the collective brain of the group to clarify the vagueness and confusion surrounding the quot;MVCquot; term... ------------------------------------------------------------------------------------------------------------------------------ quot;the elusive wisdomquot; quot;MVCquot; - the three-letter acronym is used a lot... working within IT/SE/SD industry one does constantly encounter it these days - it is mentioned everywhere, but when trying to clearly quot;see itquot; and quot;get itquot; then in some of (if not in the most of) the contexts in which it is been mentioned these days you'd often get a feeling that it quot;escapes youquot;... Consulting the original source (i.e. quot;MVCquot; in SmallTalk-80) to which a reference is usually and routinely made in those contexts where the quot;MVCquot; buzzword is used does NOT help, rather on the contrary - as very often even with allowing some extrapolation and interpretation it is quite hard to match the original thing with what you actually have in this other contexts (these quot;other contextquot; come in various forms and shapes - UI frameworks, web-app frameworks, CMS, quot;blueprintsquot;, quot;product/system architecturesquot; etc...) This leads to frustration as you get a feeling that there is some non-esoteric but rather fairly trivial (because everyone uses and applies it routinely and easily) piece of knowledge and/or a concept that everyone around possesses and operates with fluently, but which escapes YOU personally !! :( Did anyone feel like that? You are NOT alone!! ;) But what is even more interesting is the fact the people who are renown OO and Design Patterns experts and who really used SmallTalk and really used the original MVC on it have the same problem with industry current use (i.e. abuse !) of the term... A good view on this phenomenon can be found in Martin Fowler's 1 online updates to his quot;Patterns of Enterprise Application Architecturequot; book http://www.martinfowler.com/eaaDev/uiArchs.html quot;...Probably the widest quoted pattern in UI development is Model View Controller (MVC) - it's also the most misquoted. I've lost count of the times I've seen something described as MVC which turned out to be nothing like it. Frankly a lot of the reason for this is that parts of classic MVC don't really make sense for rich clients these days. ..quot; And then, in that part of the article he strives to communicate the REAL meaning of MVC in its original sense and explain how it is not really applicable nowadays... 1 No, I don’t work for ThoughtWorks ;)
  • 2. But the rest of the industry is not as pedantic and rather than striving for technical correctness and preciseness is embracing a use of quot;MVCquot; in a very broad and vague sense, more like a “buzzword”. The trick is that as in fact one should expect of anything that has escaped from the domain of the experts and specialist into the a domain of journalists, marketing/salespersons and quot;mass triviaquot; (quot;mass culturequot;) it is been used rather superficially and with deliberate vagueness, the intention often been to be quot;buzzword-compliantquot; rather then to infer some precise technical meaning... A somewhat harsh, but true summary of this phenomenon is given at (good for it’s discussion and comments) quot;C2quot; resource (Cunningham & Cunningham, Inc.) on quot;MVCquot;: http://c2.com/cgi/wiki?ModelViewController quot;...When a system obeys the principle DoTheMostComplexThingThatCouldPossiblyWork, marketects often respond by clumping its rambling notions together into 3 groups. The sub-SpaghettiCode group nearest the User becomes the quot;viewquot;, that nearest the database becomes the quot;modelquot;, and the stuff in between becomes the quot;controllerquot;. Marketects then refer to their project's architecture as quot;MVCquot;, borrowing that acronym's impressive lineage...quot; In fact comments like that make this quot;C2quot; wiki on MVC quite an interesting resource, much in contrast with Wikipedia's http://en.wikipedia.org/wiki/Model-view-controller which, IMHO, serves more as an illustration of what I dubbed as superficial quot;mass trivia/mass culturequot; approach... Another thing I'd like to quote found at quot;C2quot; is a good example of what the broad interpretation of quot;MVCquot; in fact allows is: quot;...Perhaps web pages are an example of this - with the 'view' being css, 'model' being html, 'control' being, in part, the browser...quot; So what you can take fro here is that when moving from precise strict meaning of MVC to the broad sense use of it, then certain (and quite large! ;) degree of vagueness, impreciseness and confusion are in fact: - inherent - deliberate - inevitable In other words, the feelings that some people feel in association with quot;MVCquot; abbreviation are quot;perfectly normalquot; in medical sense ;) So, having cleared that and ruled out the personal quot;insecurity complexquot;, we can now relax a bit and quot;let it goquot; and accept the realities of the modern world... Then, we can draw a conclusion that quot;MVCquot; (and in fact the quot;Design Patternsquot; in general) should not even be attempted to be studied as the hard science i.e. as something inherently existing in nature in some quot;true formquot;, but more like linguistics and anthropology - i.e. like things that are artificially coined by society and which evolve in certain way whether like it or not...
  • 3. (Another great example of similar kind of thing is the use of term and the concept of quot;Architecturequot; and quot;Architectquot; these days in IT/SE/SD industry and which is causing a lot of controversy, but that's a separate topic... ;) [O.K. - however can't help some more off-topic note though: there is also an older and somewhat similar controversy and confusion about quot;Software Engineeringquot; and quot;Software Engineersquot;, like is Software Engineering really engineering or what is it etc - But, you don't hear much of those sort of arguments these days - I think that's because it has been satisfactorily solved by now by the following formula: quot;Software Engineering is whatever the Software Engineers do.(period!)quot; ;] So with this quot;wisdomquot; we can quot;move onquot; and accept the various broad meanings and interpretations of quot;MVCquot;. Try to keep it “open minded”. ------------------------------------------------------------------------------------------------------------------------------ So, essentially looks like there are three meanings of quot;MVCquot; (but again with various sub- meanings inside each one! ;) 1. MVC - the actual UI framework in Smalltalk-80 2. quot;classicquot; MVC - most well described in POSA1 book (quot;Pattern-Oriented Software Architecture Volume 1: A System of Patternsquot; – surely folks here know this book) It is also mentioned in dozens of other (if not all) books on OO Design Patterns, but usually as an example/application of an OBSERVER pattern (!!) [including GoF, pp.4-5, p.303 ... quot;known usesquot; of Observer...] So POSA1 is in fact one of the rare sources which clearly catalogues it as a quot;architectural patternquot; (and, yes - there are some somewhat rather more scholastic discussion whether MVC - even in its quot;classicquot; meaning described here - whether MVC is a quot;patternquot; or a quot;composition of patterns / compound patternquot; or an quot;architecturequot; or quot;stylequot; or “approach”, “method”, “paradigm” etc etc) Now, when I was reading it in POSA1 I had some interesting quot;subconsciousquot; feelings: a feeling of low-level... quot;mouse-clickquot;... quot;key-pressedquot;... quot;drawquot;... quot;render textquot;... (?!?!) a feeling of a specific implementation solution imposed by whatever archaic platform Smalltalk-80 was running on... So interestingly, this somewhat relates again with MVC section in Fowler's http://www.martinfowler.com/eaaDev/uiArchs.html quot;... As we look at MVC it's important to remember that this was one of the first attempts to do serious UI work on any kind of scale. Graphical User Interfaces were not exactly common in the 70's. The Forms and Controls model I've just described came after MVC - I've described it first because it's simpler, not always in a good way. Again I'll discuss
  • 4. Smalltalk 80's MVC using the assessment example - but be aware that I am taking a few liberties with the actual details of Smalltalk 80 to do this - for start it was monochrome system... And again, as I said earlier M. Fowler goes into precise details describing the genuine original quot;Truequot; MVC… one more quote which I think is especially notable too quot;... At this point I should stress that there's not just one view and controller, you have a view-controller pair for each element of the screen, each of the controls and the screen as a whole. quot; This in fact coincides and matches very well the MVC design arrangement described (quite decently and thoroughly) in POSA1and also as mentioned earlier the Fowler’s article then explains how the realities are different these days and how most of widely-used UI frameworks/technologies are not strictly speaking an MVC (WinForms, WebForms, all those other “Forms” and “Pages” etc) and that most of nowadays rich-UI development paradigms can follow better under Model-View-Presenter approach Note that what is usually emphasized by quot;MVC puristsquot; are the following two aspects of quot;genuinequot; MVC: - the aspect of the Controller (in fact MANY controllers, as in the above quote) - the aspect of Observer (many opinions in this regard can be found again on http://c2.com/cgi/wiki?ModelViewController) POSA1 on another hand takes a bit more relaxed approach and allows more broad interpretations thus allowing all of the GUI/Windowing frameworks (let’s focus on the non-Web ones - they are separate story address below) to have their place under MVC as quot;variantsquot;... And the first thing that gets sacrificed is the presence of the Controller(s) as separate object(s): “ … Document-View This variant relaxes the separation of view and controller. In several GUI platforms, window display and event handling are closely interwoven. For example, the X Window System reports events relative to a window. You can combine the responsibilities of the view and the controller from MVC in a single component by sacrificing exchangeability of controllers. This kind of structure is often called a Document-View architecture [App89], [Gam91], [Kru96]. The document component corresponds to the model in MVC, and also implements a change-propagation mechanism. The view component of Document-View combines the responsibilities of controller and view in MVC, and implements the user interface of the system. …” So this explains why it is sometimes hard to see the MVC in where it is supposedly present - like in some GUI framework you are using (again let's leave web-app ones aside for the moment... because most of the time you are in fact using either something similar to Model-View-Presenter or even most likely a Document-View one... Interestingly many things which are very often quoted and strongly associated with MVC, are still not MVC in strong sense…
  • 5. The only one that comes somewhat especially (and deliberately) close to true MVC is Java's Swing... but still there quot;interestingquot; subtleties... From http://en.wikipedia.org/wiki/Model-view-controller Java Swing Java Swing is different from the other frameworks, in that it supports two MVC patterns. Model (Frame level) Like the other frameworks, the design of the real model is usually left to the developer. Model (Control level) Swing also supports models on the control level. Unlike other frameworks, Swing exposes the internal storage of each control as a model. [** O.K. comment: here I think Swing designers did a deliberate attempt to approximate the original Smalltalk’s MVC] View The view is represented by a class that inherits from Component. Controller Java Swing doesn't necessarily use a single controller. Because its event model is based on interfaces, it is common to create an anonymous action class for each event. In fact, the real controller is in a separate thread. It catches and propagates the events to the view and model. This is also brings to mind the question most people have in regards to quot;MVCquot; – quot;but where's the Controller...?quot; (and sometimes the answer is in the realm of something like quot;well... Controller is ... everything else after you taken out the Model and the View...quot; ;) There is even an dedicated resource (again on C2 wiki) for this question: http://c2.com/cgi/wiki?WhatsaControllerAnyway Also an interesting point of discussion is the level at which MVC is to be considered? Addressing the MODEL aspect on itself… For example is the Model really something low level such as “the number representing position of scrollbar” – an example often given as MVC example, especially in Swing literature… Or is Model really something at higher more conceptual level – ie.e Domain Model. Looks like there is no strict consensus here either it is open for broad and flexible interpretation. ----
  • 6. But all for all, all these variations are still nevertheless reasonably close to the quot;classic MVCquot; and for definition of quot;classic MVCquot; which I think it is sensible to accept the what’s given in POSA1 and all the variations it quot;allowsquot;... And one thing that is notably still present in all these variations is the use of classical OBSERVER pattern in classical OO Design patterns sense... This leads us to the most quot;broad sensequot; of the quot;MVCquot; acronym, which also lately happens to be the prevailing use of it (due to Web-apps, quot;J2EEquot;, “Ruby on Rails” etc) 3. quot;Web MVCquot; - basically the “classic MVC” has became more of quot;METAPHORquot; in the context of web-applications rather then something used in its original OOD sense... On a web this metaphor stands for an “architectural style” of separating presentation (quot;viewquot;) from the business data/logic (quot;modelquot;) or even for merely quot;... separating INPUT, PROCESSING and OUTPUTquot;... Most interestingly, the original strong association between MVC and OBSERVER pattern is totally lost as the quot;propagation mechanismquot; has become a quot;poll mechanismquot; - i.e. refreshing the browser (!!) (AJAX might be altering this aspect a bit lately - although it still remains a POLL mechanism!... but here we talk more about quot;traditionalquot; quot;Web-MVCquot; - J2EE design blueprints, Struts etc... ) Some people think that to a great extent this quot;MVC metaphorquot; for web-apps was quot;inventedquot; and pushed and promoted by Sun/J2EE and its marketing forces... quot;Model 1 and Model 2quot;, quot;blueprintsquot; etc… Let’s reproduce again that quote from C2 wiki http://c2.com/cgi/wiki?ModelViewController in it's entirety (emphasis added) quot;...When a system obeys the principle DoTheMostComplexThingThatCouldPossiblyWork, marketects often respond by clumping its rambling notions together into 3 groups. The sub- SpaghettiCode group nearest the User becomes the quot;viewquot;, that nearest the database becomes the quot;modelquot;, and the stuff in between becomes the quot;controllerquot;. Marketects then refer to their project's architecture as quot;MVCquot;, borrowing that acronym's impressive lineage. Sounds like SunMicrosystems's JavaLanguage PetStore...quot; To some extent the Java/J2EE has restored some more credibility to the quot;MVCquot; term use (but still in quot;metaphoricalquot; sense, or if you prefer quot;at a level of abstraction higher than the OODquot; sense... this is not a quiet – I just made it up myself right now ;) This took form in such reasonably successful efforts as Struts, and later on, JSF
  • 7. But again I’d like to throw in some interesting excerpt from a Struts book emphasis added): ---------------------------------------------------- Jakarta Struts Cookbook By Bill Siggelkow You often hear Struts referred to as a model-view-controller (MVC) framework for web applications. Struts can help you build web applications that separate the data (model) from the presentation (view); however, Struts doesn't provide a framework for the model. Rather, it supports custom Actions which broker the interaction between the view and model. ... Though Struts is referred to as an MVC framework for web applications, Struts doesn't attempt to provide the model of that paradigm. Struts provides only the bridge between the view and the model, Struts Actions. An Action shouldn't access the database; an Action shouldn't need to know how the data is stored and accessed. Instead, an Action acts as a thin façade to your business services, marshalling data from the view to the model and back. The following FAQ from the Struts web site puts it quite succinctly: Ideally, all the database access code should be encapsulated behind the business API classes, so Struts doesn't know what persistence layer you are using (or even if there is a persistence layer). It passes a key or search String and gets back a bean or collection of beans. This lets you use the same business API classes in other environments, and lets you run unit tests against your business API outside of Struts or a HTTP environment. While Struts does support the data-source element for configuring JDBC data sources, the Struts release notes state that this element may not be supported in the future. According to the Struts documentation, you should use the data-source element when you need to pass a javax.sql.DataSource to a legacy API. This results in a dependency between the Action and the persistence layer as illustrated in As a result of “Web MVC” trend, the latest of POSA series books - POSA4 (which largely revisits most of POSA1 and POSA2 from the perspective of nowadays - i.e quot;10 years afterquot;… but wrapps it in a context of “distributed systems” ) and POSA5 have been reflecting this quot;new realityquot; and quot;legitimizesquot; the de facto broad meaning of quot;MVCquot; term ----------------------------------------------- POSA4 Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (Hardcover) by Frank Buschmann (Author), Kevlin Henney (Author), Douglas C. Schmidt (Author) p.188 Divide the interactive application into three decoupled parts: processing, input and output. Ensure the consistency of the three parts with the help of a change propagation mechanism. ... A Model-View-Controller arrangement separates responsibilities of an application that tend to change at a different rate, to support their independent evolution. --------------------------------------------- ------------------------------------------------------------------------------------------------------------ POSA5 Model-View- Controller (MVC)
  • 8. The MODEL-VIEW-CONTROLLER pattern [POSA1] [POSA4] [Fow02] divides an interactive application with respect to three roles. The model contains the core functionality and data. Views display information to the user. Controllers handle user input. Views and controllers together comprise the user interface. A change-propagation mechanism ensures consistency between the user interface and the model. ----------------------------------------- I personally still however feel that in case of quot;Web MVCquot; a browser refresh is a bit of a stretch for quot;change propagation mechanismquot; (again, AJAX is altering the landscape somewhat but it is still a POLL mechanism !! ;) So I guess we shall just accept this “high-abstraction-level” and decoupled from OOD meaning of the “MVC” in case of “Web MVC”… I guess on a Web the “Web MVC” is just as close approximation of the “MVC” metaphor as you can get as is the iGoogle “desktop” (or whatever it’s called) an approximation of my real (office furniture) desktop metaphor.. ;) Basically we are dealing with a linguistic phenomenon where and old word “MVC” has evolved to a substantially different NEW meaning… --------------------------------------------------------------------------------------------------------------------------------- Questions for group discussion at UG meeting: who used quot;MVCquot; in his/her design or thinks/knows that some framework been used is quot;MVCquot;? (in ANY meaning of quot;MVCquot; !!) is WinForm MVC? WebForms? is Swing MVC ? is AWT? SWT? what about Delphi and alike?... VB? 3rd party quot;rich-GUI-controlsquot; - DevExpress, Dundas etc? what form did controller(s) take? did you really use a separate object for controller? (probably not, as most platfomrs/frameworks implement quot;Document-Viewquot; see POSA1 pp.140-141,143) now to quot;Web MVCquot; ASP.NET? JSPs? Struts? JSF? Ruby-On-Rails?
  • 9. APPENDIX. Clippings and quotations from various books and sometimes links they give Might use some of these for discussion purposes… ------------------------------------------------------------------------------------------------------------ POSA 4 p.174 ... The Model-View- Presenter [Fow06] is also related to Model-View-Controller, but works better for rich client development than MVC because it does not delegate all view behavior to the model. An intermediate presenter component receives all user actions, such as when clicking a checkbox, or if the involvement of the model is necessary, such as when clicking an 'Apply' button, and decides whether it can handle them without consulting the model. This improves composability of complex views and the testability of the different roles. [Fow06] M. Fowler: The Model-View-Presenter Pattern, http://martinfowler.com/eaaDev/ModelViewPresenter.html, 2006 M. FOWLER HAS quot;RETIREDquot; THIS RECENTLY - SPLIT INTO TWO OTHER THINGS... http://geekswithblogs.net/billy/archive/2006/07/20/85815.aspx http://www.darronschall.com/weblog/archives/000113.cfm http://martinfowler.com/eaaDev/uiArchs.html http://msdn.microsoft.com/msdnmag/issues/06/08/DesignPatterns/default.aspx ----- http://www.codeproject.com/aspnet/ModelViewPresenter.asp Model-View-Presenter Model-View-Presenter (MVP) is a variation of the Model-View-Controller (MVC) pattern but specifically geared towards a page event model such as ASP.NET. For a bit of history, MVP was originally used as the framework of choice behind Dolphin Smalltalk. The primary differentiator of MVP is that the Presenter implements an Observer design of MVC but the basic ideas of MVC remain the same: the model stores the data, the view shows a representation of the model, and the presenter coordinates communications between the layers. MVP implements an Observer approach with respect to the fact that the Presenter interprets events and performs logic necessary to map those events to the proper commands to manipulate the model. For more reading on MVC vs. MVP, take a look at Darron Schall's concise entry on the subject. What follows is a detailed examination of MVP in the form of three example projects.
  • 10. Author's note: Martin Fowler has suggested that MVP be split between two quot;newquot; patterns called Supervising Controller and Passive View. Go here for a very short synopsis of the split. The content described herein is more consistent with Supervising Controller as the View is aware of the Model. --------------------------------------------------------------------------------------------------------------------------------- Refactoring: Improving the Design of Existing Code Martin Fowler-- Whenever you hear people talking about objects, you hear about model-view-controller (MVC). This idea underpinned the relationship between the graphical user interface (GUI) and domain objects in Smalltalk-80. The gold at the heart of MVC is the separation between the user interface code (the view, these days often called the presentation) and the domain logic (the model). The presentation classes contain only the logic needed to deal with the user interface. Domain objects contain no visual code but all the business logic. This separates two complicated parts of the program into pieces that are easier to modify. It also allows multiple presentations of the same business logic. Those experienced in working with objects use this separation instinctively, and it has proved its worth. But this is not how most people who work with GUIs do their design. Most environments with client-server GUIs use a logical two-tier design: the data sits in the database and the logic sits in the presentation classes. The environment often forces you toward this style of design, making it hard for you to put the logic anywhere else. Java is a proper object-oriented environment, so you can create nonvisual domain objects that contain business logic. However, you'll often come across code written in the two-tier style. --------------------------------------------------------------------------------------------------------------------------------- Thinking in C# Larry O’Brien and Bruce Eckel p.577 Model-View-Controller Model-View-Controller, commonly referred to simply as “MVC,” was the first widely known architectural pattern for decoupling the graphical user interface from underlying application logic. Unfortunately, many people confuse MVC with any architecture that separates presentation logic from domain logic. So when someone starts talking about MVC, it’s wise to allow for quite a bit of imprecision. In MVC, the Model encapsulates the system’s logical behavior and state, the View requests and reflects that state on the display, and the Controller interprets lowlevel inputs such as mouse and keyboard strokes, resulting in commands to either the Model or the View. MVC trades off a lot of static structure — the definition of objects for each of the various responsibilities – for the advantage of being able to independently vary the view and the controller. This is not much of an advantage in Windows programs, where the view is always a bitmapped two-dimensional display and the controller is always a combination of a keyboard and a mouse-like pointing device. However, USB’s widespread support has already led to interesting new
  • 11. controllers and the not-so-distant future will bring both voice and gesture control and “hybrid reality” displays to seamlessly integrate computer-generated data into real vision (e.g., glasses that superimpose arrows and labels on reality). If you happen to be lucky enough to be working with such advanced technologies, MVC may be just the thing. Even if not, it’s worth discussing briefly as an example of decoupling GUI concerns taken to the logical extreme. In our example, our domain state is simply an array of Boolean values; we want the display to show these values as buttons and display, in the title bar, whether all the values are true or whether some are false: ... p.581 The clear delineation of duties in MVC is appealing – the View passively reflects the Model, the Controller mediates updates, and the Model is responsible only for itself. You can have many View classes that reflect the same Model (say, one showing a graph of values, the other showing a list) and dynamically switch between them. However, the structural complexity of MVC is a considerable burden and is difficult to “integrate” with the Visual Designer tool. ------------------------------------------------------------------------------------------------------------ Java Swing Copyright © 1998 O'Reilly & Associates, Inc. All rights reserved. p.22 1.4 The Model-View-Controller Architecture Swing uses the model-view-controller architecture (MVC) as the fundamental design behind each of its components. Essentially, MVC breaks GUI components into three elements. Each of these elements plays a crucial role in how the component behaves. ... p.23 1.4 The Model-View-Controller Architecture Swing uses the model-view-controller architecture (MVC) as the fundamental design behind each of its components. Essentially, MVC breaks GUI components into three elements. Each of these elements plays a crucial role in how the component behaves. ----------------------------------------------------------------------------------------------------------------
  • 12. --------------------------------------------------------------------------------------------- Java™ Design Patterns: A Tutorial By James W. Cooper Publisher : Addison Wesley Pub Date : January 28, 2000 ISBN: 0-201-48539-7 Pages : 352 The MVC Architecture as an Observer As we noted in Chapter 3, the JList, JTable, and JTree objects all operate as observers of a data model. In fact, all of the visual components derived from JComponent can have this same division of labor between the data and the visual representation. In JFC parlance, this is referred to as the Model-View-Controller (MVC) architecture, where the data are represented by the Model, and the View by the visual component. The Controller is the communication between the Model and View objects, and may be a separate class or it may be inherent in either the model or the view. This is the case for the JFC components, and they are all examples of the Observer pattern we’ve just been discussing. ---------------------------------------------------------------------------------------------------------------- Natalie Levi with Philip Heller Java ™ 2: Web Developer Certification Study Guide A project’s success is often measured by its immediate return value, and its future ability to expand, change, be maintained, and adapt. Most applications should be written with extensibility in mind; this means changes or additions do not break existing components. The Model View Controller design pattern is geared toward creating an application that can increase client-side functionality without warranting changes to the server-side code. The pattern was originally developed by using the language SmallTalk and later gained popularity in the Java market through its extensive use within the Swing component library. The pattern takes a single graphical object and breaks down its tasks into three pieces: _ The controller, which triggers a change to the component _ The model, which manages the data by providing methods to alter or access the information _ The view, which provides a visual display of the current data A scrollbar component is a perfect example of MVC in action. It has a few controllers, both up and down buttons, plus the slider. When any of these elements is used, the controller invokes the model. The data associated with a scrollbar is usually an int value that represents the location of the slider. The up-arrow controller tells the model to increase the int value, and the down-arrow controller calls the model’s method to decrease the value. It is then the model’s responsibility to update the data and notify listeners or views interested in the recently changed data. Figure 11.8 provides a visual representation of each MVC component within a scrollbar. FIGURE 1 1 . 8 MVC within a scrollbar Model int value = 1; View Controller Controller Model View Controller Pattern 439 The class that handles the visual presentation is notified of a change and is
  • 13. able to repaint the image to correctly represent the current data. In this case, the slider would be repositioned to represent the increase or decrease in value. The benefits you gain from creating three classes, rather than two or one, are as follows: _ Changes to the controller do not affect any view classes. _ Changes to the view do not affect any controller classes. _ You can add additional view or controller classes without affecting existing code. By removing the data from the graphical components and by separating these components into two categories, one that controls and one that displays, you create an application environment that is easily extensible. The order of operations is as follows: 1. When the controller is triggered, it communicates a change to the model. 2. The model makes a change to the data and pushes the new data to the appropriate views. 3. The view receives the new data and displays the new image or form. ------------------------------------------------------------------------------------------------------------ Learning Java Pat Niemeyer Jonathan Knudsen Publisher: O'Reilly First Edition May 2000 ISBN: 1-56592-718-4, 722 pages Before continuing our discussion of GUI concepts, we want to make a brief aside and talk about the Model/View/Controller (MVC) framework. MVC is a method of building reusable components that logically separates the structure, presentation, and behavior of a component into separate pieces. MVC is primarily concerned with building user interface components, but the basic ideas can be applied to many design issues; its principles can be seen throughout Java. The fundamental idea behind MVC is the separation of the data model for an item from its presentation. For example, we can draw different representations (e.g., bar graphs, pie charts) of the data in a spreadsheet. The data is the model ; the particular representation is the view . A single model can have many views that present the data differently. A user interface component's controller defines and governs its behavior. Typically, this includes changes to the model, which, in turn, cause the view(s) to change, also. For a checkbox component, the data model could be a single boolean variable, indicating whether it's checked or not. The behavior for handling mouse-press events would alter the model, and the view would examine that data when it draws the on-screen representation. The way in which Swing objects communicate, by passing events from sources to listeners, is part of this MVC concept of separation. Event listeners are quot;observersquot; (controllers) and event sources are quot;observablesquot; (models). When an observable changes or performs a function, it notifies all of its observers of the activity. Swing components explicitly support MVC. Each component is actually composed of two pieces. One piece, called the UI-delegate, is responsible for the quot;viewquot; and quot;controllerquot; roles. It takes care of drawing the component and responding to user events. The second piece is the data model itself. This separation makes it possible for multiple Swing components to share a single data model. For example, a read-only text box and a drop-down list box could use the same list of strings as a data model.
  • 14. 15.1 Text Components Swing gives us sophisticated text components, from plain text entry boxes to HTML interpreters. For full coverage of Swing's text capabilities, see Java Swing, by Robert Eckstein, Marc Loy, and Dave Wood (O'Reilly & Associates). In that encyclopedic book, six meaty chapters are devoted to text. It's a huge subject; we'll just scratch the surface here. Let's begin by examining the simpler text components: JTextArea is a multiline text editor; JTextField is a simple, single-line text editor. Both JTextField and JTextArea derive from the JTextComponent class, which provides the functionality they have in common. This includes methods for setting and retrieving the displayed text, specifying whether the text is quot;editablequot; or read-only, manipulating the cursor position within the text, and manipulating text selections. Observing changes in text components requires an understanding of how the components implement the Model-View-Controller (MVC) architecture. You may recall from the last chapter that Swing components implement a true MVC architecture. It's in the text components that you first get an inkling of a clear separation between the M and VC parts of the MVC architecture. The model for text components is an object called a Document. When you add or remove text from a JTextField or a JTextArea, the corresponding Document is changed. It's the document itself, not the visual components, that generates text events when something changes. To receive notification of JTextArea changes, therefore, you register with the underlying Document, not with the JTextArea component itself: JTextArea textArea = new JTextArea( ); Document d = textArea.getDocument( ); d.addDocumentListener(someListener); As you'll see in an upcoming example, you can easily have more than one visual text component use the same underlying data model, or Document. In addition, JTextField components generate an ActionEvent whenever the user presses the Return key within the field. To get these events, implement the ActionListener interface, and call addActionListener( ) to register. Model-View-Controller (MVC) framework A user-interface design that originated in Smalltalk. In MVC, the data for a display item is called the quot;model.quot; A quot;viewquot; displays a particular representation of the model, and a quot;controllerquot; provides user interaction with both. Java incorporates many MVC concepts The Model-View-Controller Paradigm Many GUI toolkits (aside from visual tools like Visual Basic or Powerbuilder) partition the classes into user interface and application data classes. (These are sometimes referred to as the presentation and logic layers.) Smalltalk-80 bestowed upon us the Model/View/Controller (MVC) architecture for presentation and logic layers. MVC refines the idea of presentation and logic layers by introducing another partition. An MVC triad consists of cooperating objects: the Model, the View, and the Controller. The Controller and View are typically user interface objects. The Controller allows a user to modify the Model. Once modified, the Model notifies the View that a change has occurred. The View queries the Model and displays the updated information. By separating the objects this way, the interactions are greatly simplified, the coupling is reduced, and the responsibilities of each object are very clear. The Model never has a user interface component. The View never changes the
  • 15. Model. The Controller never directly interacts with the View. Figure 23.9 shows the connections in an application with one Model, two Views, and two Controllers. You can see that the upper half of the figure looks just like the connections between an Observable and two Observers. Of course, that is hardly a coincidence. In many ways, you can consider MVC as one of the earliest occurrences of the Observer pattern. Figure 23.9: An example of a Model-View-Controller architecture. Although Java does not directly refer to MVC, the built-in Observer mechanism forms the foundation upon which you can build MVC applications. Java applications built with an MVC architecture evolve well over time. They can easily adopt new interfaces, new models, and new displays. Ideally, each component of MVC can be replaced or reused independently of the whole. -------------------------------------------------------------------------------------- --------------------------------------------------------------------------- Java Concurrency in Practice By Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea ............................................... Publisher: Addison Wesley Professional Pub Date: May 09, 2006 Print ISBN-10: 0-321-34960-1 Print ISBN-13: 978-0-321-34960-6 Pages: 384 9.1. Why are GUIs Single-threaded? In the old days, GUI applications were single-threaded and GUI events were processed from a quot;main event loopquot;. Modern GUI frameworks use a model that is only slightly different: they create a dedicated event dispatch thread (EDT) for handling GUI events. Single-threaded GUI frameworks are not unique to Java; Qt, NextStep, MacOS Cocoa, X Windows, and many others are also single-threaded. This is not for lack of trying; there have 149 been many attempts to write multithreaded GUI frameworks, but because of persistent problems with race conditions and deadlock, they all eventually arrived at the single-threaded event queue model in which a dedicated thread fetches events off a queue and dispatches them to applicationdefined event handlers. (AWT originally tried to support a greater degree of multithreaded access, and the decision to make Swing single-threaded was based largely on experience with AWT.) Multithreaded GUI frameworks tend to be particularly susceptible to deadlock, partially because of the unfortunate interaction between input event processing and any sensible object-oriented modeling of GUI components. Actions initiated by the user tend to quot;bubble upquot; from the OS to the applicationa mouse click is detected by the OS, is turned into a quot;mouse clickquot; event by the toolkit, and is eventually delivered to an application listener as a higher level event such as a quot;button pressedquot; event. On the other hand, application-initiated actions quot;bubble downquot; from the application to the OSchanging the background color of a component originates in the application and is dispatched to a specific component class and eventually into the OS for rendering. Combining this tendency for activities to access the same GUI objects in the opposite order with the requirement of making each object thread-safe yields a recipe for inconsistent lock ordering, which leads to deadlock (see Chapter 10). And this is exactly what nearly every GUI toolkit development effort rediscovered through experience.
  • 16. Another factor leading to deadlock in multithreaded GUI frameworks is the prevalence of the model-view-control (MVC) pattern. Factoring user interactions into cooperating model, view, and controller objects greatly simplifies implementing GUI applications, but again raises the risk of inconsistent lock ordering. The controller calls into the model, which notifies the view that something has changed. But the controller can also call into the view, which may in turn call back into the model to query the model state. The result is again inconsistent lock ordering, with the attendant risk of deadlock. In his weblog,[1] Sun VP Graham Hamilton nicely sums up the challenges, describing why the multithreaded GUI toolkit is one of the recurring quot;failed dreamsquot; of computer science. [1] http://weblogs.java.net/blog/kgh/archive/2004/10 I believe you can program successfully with multithreaded GUI toolkits if the toolkit is very carefully designed; if the toolkit exposes its locking methodology in gory detail; if you are very smart, very careful, and have a global understanding of the whole structure of the toolkit. If you get one of these things slightly wrong, things will mostly work, but you will get occasional hangs (due to deadlocks) or glitches (due to races). This multithreaded approach works best for people who have been intimately involved in the design of the toolkit. Unfortunately, I don't think this set of characteristics scales to widespread commercial use. What you tend to end up with is normal smart programmers building apps that don't quite work reliably for reasons that are not at all obvious. So the authors get very disgruntled and frustrated and use bad words on the poor innocent toolkit. Single-threaded GUI frameworks achieve thread safety via thread confinement; all GUI objects, including visual components and data models, are accessed exclusively from the event thread. Of course, this just pushes some of the thread safety burden back onto the application developer, who must make sure these objects are properly confined. --------------------------------------------------------------------------- “Web MVC” -------------------------------- Excerpted from: Core Servlets and JavaServer Pages, Vol. 1: Core Technologies, Second Edition by Marty Hall, Larry Brown MVC Frameworks The key motivation behind the MVC approach is the desire to separate the code that creates and manipulates the data from the code that presents the data. The basic tools needed to implement this presentation-layer separation are standard in the Simple application or small development team. Complex application or large development team. • Call Java code directly. Place all Java code in JSP page. Appropriate only for very small amounts of code. Chapter 11. • Call Java code indirectly. Develop separate utility classes. Insert into JSP page only the Java code needed to invoke the utility classes. Chapter 11. • Use beans. Develop separate utility classes structured as beans. Use jsp:useBean, jsp:getProperty, and jsp:setProperty to invoke the code. Chapter 14
  • 17. • Use the MVC architecture. Have a servlet respond to original request, look up data, and store results in beans. Forward to a JSP page to present results. JSP page uses beans. This chapter. • Use the JSP expression language. Use shorthand syntax to access and output object properties. Usually used in conjunction with beans and MVC. Chapter 16. • Use custom tags. Develop tag handler classes. Invoke the tag handlers with XML-like custom tags. Volume 2. 15.2 Implementing MVC with RequestDispatcher 437 servlet API and are the topic of this chapter. However, in very complex applications, a more elaborate MVC framework is sometimes beneficial. The most popular of these frameworks is Apache Struts; it is discussed at length in Volume 2 of this book. Although Struts is useful and widely used, you should not feel that you must use Struts in order to apply the MVC approach. For simple and moderately complex applications, implementing MVC from scratch with RequestDispatcher is straightforward and flexible. Do not be intimidated: go ahead and start with the basic approach. In many situations, you will stick with the basic approach for the entire life of your application. Even if you decide to use Struts or another MVC framework later, you will recoup much of your investment because most of your work will also apply to the elaborate frameworks. Architecture or Approach? The term “architecture” often connotes “overall system design.” Although many systems are indeed designed with MVC at their core, it is not necessary to redesign your overall system just to make use of the MVC approach. Not at all. It is quite common for applications to handle some requests with servlets, other requests with JSP pages, and still others with servlets and JSP acting in conjunction as described in this chapter. Do not feel that you have to rework your entire system architecture just to use the MVC approach: go ahead and start applying it in the parts of your application where it fits best. ----------------------------------------------------------------------------------------------------------------------------- Designing Enterprise Applications with the J2EETM Platform, Second Edition Inderjeet Singh, Beth Stearns, Mark Johnson, and the Enterprise Team 4.4 Web-Tier Application Framework Design Model-View-Controller (“MVC”) is the BluePrints recommended architectural design pattern for interactive applications. MVC, described in Chapter 11, organizes an interactive application into three separate modules: one for the application model with its data representation and business logic, the second for views that provide data presentation and user input, and the third for a controller to dispatch requests and control flow. Most Web-tier application frameworks use some variation of the MVC design pattern. The MVC design pattern provides a host of design benefits. MVC separates design concerns (data persistence and behavior, presentation, and control), decreasing code duplication, centralizing control, and making the application more easily modifiable. MVC also helps developers with different skill sets to focus on
  • 18. their core skills and collaborate through clearly defined interfaces. For example, a J2EE application project may include developers of custom tags, views, applica- WEB-TIER APPLICATION FRAMEWORK DESIGN 95 tion logic, database functionality, and networking. An MVC design can centralize control of such application facilities as security, logging, and screen flow. New data sources are easy to add to an MVC application by creating code that adapts the new data source to the view API. Similarly, new client types are easy to add by adapting the new client type to operate as an MVC view. MVC clearly defines the responsibilities of participating classes, making bugs easier to track down and eliminate. This section describes how to use MVC to organize a J2EE Web application design using the sample application’s Web Application Framework design as an example. Many of the key classes described (the controller, the templating service, the abstract action class, and so on) are usable for any application, not just for an online shopping application. A J2EE application’s Web tier serves HTTP requests. At the highest level, the Web tier does four basic things in a specific order: interprets client requests, dispatches those requests to business logic, selects the next view for display, and generates and delivers the next view. (See Figure 4.2.) The Web-tier controller receives each incoming HTTP request and invokes the requested business logic operation in the application model. Based on the results of the operation and state of the model, the controller then selects the next view to display. Finally, the controller generates the selected view and transmits it to the client for presentation. Figure 4.2 is deceptively simple. An enterprise application’s Web tier commonly has the following requirements: The Web-tier controller receives each incoming HTTP request and invokes the requested business logic operation in the application model. Based on the results of the operation and state of the model, the controller then selects the next view to display. Finally, the controller generates the selected view and transmits it to the client for presentation. Figure 4.2 is deceptively simple. An enterprise application’s Web tier commonly has the following requirements: 96 CHAPTER 4 THE WEB TIER • An application design must have a strategy for serving current and future client types. • A Web-tier controller must be maintainable and extensible. Its tasks include mapping requests to application model operations, selecting and assembling views, and managing screen flow. Good structure can minimize code complexity. • Application model API design and technology selection have important implications for an application’s complexity, scalability, and software quality. • Choosing an appropriate technology for generating dynamic content improves development and maintenance efficiency. The BluePrints best practice is to implement the Web tier of a J2EE enterprise application using an appropriate Web application framework. (See Section 4.4.5 on page 114.) The next several sections describe the general design of a J2EE application Web tier. If you choose to use a Web application framework, the following discussion will help you to understand what the framework does and how to use it. If you write your own Web-tier architectural code, the following design
  • 19. discussions will help you make educated decisions about how to use the technology. 4.4.1 Structuring the Web Tier Overall structure is the most important consideration in a Web-tier design. Both the sample application and the various existingWeb application frameworks implement some form of “Model 2” architecture, where a servlet manages client communication and business logic execution, and presentation resides mainly in JSP pages. The literature on Web-tier technology in the J2EE platform frequently uses the terms “Model 1” and “Model 2” without explanation. This terminology stems from early drafts of the JSP specification, which described two basic usage patterns for JSP pages. While the terms have disappeared from the specification document, they remain in common use. Model 1 and Model 2 simply refer to the absence or presence (respectively) of a controller servlet that dispatches requests from the client tier and selects views. A Model 1 architecture consists of a Web browser directly accessing Web-tier JSP pages. The JSP pages access Web-tier JavaBeans that represent the application model, and the next view to display (JSP page, servlet, HTML page, and so on) is determined either by hyperlinks selected in the source document or by WEB-TIER APPLICATION FRAMEWORK DESIGN 97 request parameters. A Model 1 application control is decentralized, because the current page being displayed determines the next page to display. In addition, each JSP page or servlet processes its own inputs (parameters from GET or POST). In some Model 1 architectures, choosing the next page to display occurs in scriptlet code, but this usage is considered poor form. (See the design guideline Section 4.2.6.8 on page 89.) A Model 2 architecture introduces a controller servlet between the browser and the JSP pages or servlet content being delivered. The controller centralizes the logic for dispatching requests to the next view based on the request URL, input parameters, and application state. The controller also handles view selection, which decouples JSP pages and servlets from one another. Model 2 applications are easier to maintain and extend, because views do not refer to each other directly. The Model 2 controller servlet provides a single point of control for security and logging, and often encapsulates incoming data into a form usable by the back-end MVC model. For these reasons, the Model 2 architecture is recommended for most interactive applications. An MVC application framework can greatly simplify implementing a Model 2 application. Application frameworks such as Apache Struts and JavaServer FacesTM (see Section 4.4.5 on page 114) include a configurable front controller servlet, and provide abstract classes that can be extended to handle request dispatches. Some frameworks include macro languages or other tools that simplify application construction. The Model 1 architecture can provide a more lightweight design for small, static applications. Model 1 architecture is suitable for applications that have very simple page flow, have little need for centralized security control or logging, and change little over time. Model 1 applications can often be refactored to Model 2 when application requirements change. 4.4.1.0.1 When to Switch from Model 1 to Model 2 JSP pages in a Model 1 application that use scripting elements, custom tags, or JavaScript to forward requests should be refactored to Model 2. A Model 1 architecture is best when the page navigation is simple and fixed, and when a simple directory structure can represent the structure of the pages in the application. Such applications usually embed the page flow information in the links between the pages. The presence of forward in a JSP page implies that logic embedded in the page is making a decision about the next page to display. Over time, as the application grows and changes, page flow logic accumulates. The application becomes difficult to maintain because the page flow logic is 98 CHAPTER 4 THE WEB TIER
  • 20. distributed across multiple pages. The best time to switch from Model 1 to Model 2 is before this maintenance problem arises. This is why it’s usually best to choose Model 2 from the outset, basing the application on an existing Web controller framework that best meets application requirements. Model 1 remains a viable option for simple, static applications. 4.4.2 Web-Tier MVC Controller Design The Model 2 architecture uses servlets for processing requests and selecting views. The Front Controller architectural design pattern centralizes an application’s request processing and view selection in a single component. Each type ofWeb client sends requests to and receives responses from a single URL, simplifying client development. The Front Controller receives requests from the client and dispatches them to the application model. This single point of dispatch makes the Front Controller a logical place for such global facilities as security and logging. The Front Controller also selects and formats the next client view. The controller is also an application of the Mediator pattern, because it decouples view components from one another. In the J2EE platform, a Front Controller is typically implemented as a servlet. The sample application’s Front Controller servlet handles all HTTP requests. The user views, discussed in the next section, are mostly JSP pages chosen by the Front Controller. 4.4.2.1 Web-Tier Controller Design A Web-tier MVC controller maps incoming requests to operations on the application model, and selects views based on model and session state.Web-tier controllers have a lot of duties, so they require careful design to manage complexity. Because most enterprise applications grow over time, extensibility is an important requirement. This section describes some strategies for the internal structure of a controller in the Web tier, illustrated by example code adapted from the Web Application Framework, part of the BluePrints sample application. 4.4.2.1.1 Identifying the Operation to Perform When a controller receives an HTTP request, it needs to be able to distinguish what application operation is being requested. How can the client, for example, request WEB-TIER APPLICATION FRAMEWORK DESIGN 99 that the server create a new user? There are several ways to indicate to the server which operation to perform. The more common methods include: • Indicate the operation in a hidden form field, which a POST operation delivers to the controller; for example: <FORM METHOD=quot;POSTquot; ACTION=quot;http://myServer/myApp/myServletquot;> <INPUT TYPE=quot;HIDDENquot; NAME=quot;OPquot; VALUE=quot;createUserquot;/> <!-- other form contents... --> </FORM> • Indicate the operation in a HTTP GET query string parameter; for example: http://myHost/myApp/servlets/myServlet?op=createUser • Use a servlet mapping to map all URLs with a particular suffix or base URL to a specific servlet. A servlet mapping is a deployment descriptor definition that compares request paths to a pattern and dispatches matching requests to the corresponding servlet. For example, imagine that a Web application’s deployment descriptor defines the following servlet mapping: <servlet-mapping> <servlet-name>myServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> Imagine also that the servlet’s context path is http://myServer/myApp/servlets. The servlet container would direct a request with URL http://myServer/ myApp/createUser.do myServlet to myServlet, because the request URL matches the pattern *.do. Servlet myServlet can extract the requested operation’s name from the request URL. Chapter 11 of the Java Servlet 2.3 specification defines servlet mappings.
  • 21. Of the three options discussed here, the BluePrints recommendation is to use servlet mappings when they are available. Servlet mappings provide the most flexible way to control where to route URLs based on patterns in the URLs. Most Web application frameworks (see Section 4.4.5 on page 114) use servlet mappings to direct requests to the appropriate front controller for an application. The sample application uses a servlet mapping to handle request URLs. The servlet container maps all request URLs matching *.do to the main Web-tier con- 100 CHAPTER 4 THE WEB TIER troller servlet, MainServlet.java. Another servlet mapping routes all URLs matching *.screen to the templating service, which assembles composite views. 4.4.2.1.2 Invoking Model Methods Once the controller has determined which operation to perform, it must invoke the corresponding application model method with parameters derived from the request. A naive controller design might use a large if-then-else statement, as shown in

×