You are on page 1of 76

1.2 Why OO?

1.2.1 Benefits of object-oriented programming Why has object-oriented programming gone from being ``something to think about'' to being a de-facto standard in the way software is developed today? OOA/OOD/OOP is good for:

Analyzing user requirements Designing software Constructing software o Reusability (reusable components) o Reliability o Robustness o Extensibility o Maintainability Reducing large problems to smaller, more manageable problems

According to the Gartner Institute ...


74% of all IT projects fail, come in over budget, or run past the original deadline. 28% fail altogether. 52.7% of IT projects cost 189 Every year $75B is spent on failed IT projects.

1.2.2 Symptoms of software development problems The text ``Rational Unified Process, An Introduction'' [9] identifies the following symptoms that characterize failing software development projects.

Inaccurate understanding of end-user needs. Inability to deal with changing requirements. Modules that don't fit together. Software that's hard to maintain or extend. Late discovery of serious projects flaws. Poor software quality. Unacceptable software performance. Team members in each other's way.

An untrustworthy build and release process.

1.2.3 Root causes of project failure The same text identifies the root causes of these failures:

Ad hoc requirements management. Ambiguous and imprecise communication. Brittle architectures. Overwhelming complexity. Undetected inconsistencies in requirements, designs, and implementations. Insufficient testing. Subjective project status assessment. Failure to attack risk. Uncontrolled change propagation. Insufficient automation.

1.2.4 Software development best practices Finally, the same text identifies these best practices:

Develop software iteratively. Manage requirements. Use component-based architectures. Visually model software. Verify software quality. Control changes to software.

1.3 Introduction to OO concepts What does it mean to be ``object-oriented''? The ``big three'' concepts are encapsulation, polymorphism, and inheritance, but the text ``Fundamentals of Object-Oriented Design in UML'' [12] specifies that the following criteria are necessary for a language to be considered object oriented. 1. Encapsulation - the grouping of related ideas into unit. Encapsulating attributes and behaviors. 2. Inheritance - a class can inherit its behavior from a superclass (parent class) that it extends. 3. Polymorphism - literally means ``many forms''. 4. Information/implementation hiding - the use of encapsulation to keep implementation details from being externally visible. 5. State retention - the set of values an object holds. 6. Oject identity - an object can be identified and treated as a distinct entity. 7. Message passing - the ability to send messages from one object to another. 8. Classes - the templates/blueprints from which objects are created. 9. Genericity - the construction of a class so that one or more of the classes it uses internally is supplied only at run time. 10. Test here 11. More testing here 1.3.1 Encapsulation The grouping of related items into one unit.

One of the basic concepts of OO. Attributes and behaviors are encapsulated to create objects. OO modeling is close to how we perceive the world. Implementation details are hidden from the outside world. We all know how to use a phone, few of us care how it works. The packaging of operations and attributes representing state into an object type so that state is accessible or modifiable only through the objects' interface Encapsulation lets builders of objects reuse already-existing objects, and if those objects have already been well-tested, much larger and more complex systems can be created.

1.3.2 Inheritance

A subclass is derived from a superclass. An Employee is a Person. The subclass inherits the attributes and behavior of the superclass. The subclass can override the behavior of the superclass. Notice the use of the ``Is-A'' phrase to describe inheritance. Inheritance promotes re-use.

1.3.3 Polymorphism

Literally means ``many forms''. A method can have many different forms of behavior. Commonly used between a set of classes that have a common superclass. The sender of a message does not have to know the type/class of the receiver. A single operation or attribute may be defined upon more than one class and may take on different implementations in each of those classes. An attribute may point to different objects at different times.

1.3.4 Abstraction with objects


Abstraction: the act of identifying software artifacts to model the problem domain. Classes are abstracted from concepts. This is the first step in identifying the classes that will be used in your applications. Better to have too many classes than too few. (?) When in doubt, make it a class. (?)

1.3.5 Message passing


Objects communicate by sending messages. Messages convey some form of information. An object requests another object to carry out an activity by sending it a message. Most messages pass arguments back and forth. Meilir Page-Jones defines three types of messages[12]: 1. Informative - send information for the object to update itself. 2. Interrogative - ask an object to reveal some information about itself 3. Imperative - take some action on itself, or another object Grady Booch defines four types of messages[4]:

1. Synchronous - receiving object starts only when it receives a message from a sender, and it is ready. 2. Balking - sending object gives up on the message if the receiving object is not ready to accept it. 3. Timeout - sending object waits only for a certain time period for the receiving object to be ready to accept the message. 4. Asynchronous - sender can send a message to a receiver regardless of whether the receiver is ready to receive it. 1.4 UML summary

Unified Modeling Language - UML. A modeling language, not a method. Provides a graphical representation that allows developers and architects to model a software system before the system is ever built. Analogy - an architect creating a blueprint before a house or office building is ever built. The UML does not specify a methodology/process. Therefore, saying ``We use the UML methodology is incorrect.''

A few URLs for reference:


http://www.omg.org http://www.rational.com/uml/index.jsp UML Distilled - http://www.awl.com/cseng/titles/0-201-32563-2

1.4.1 Standard diagrams The UML defines nine standard diagrams:


Use Case Class Interaction 1. Sequence 2. Collaboration Package State Activity Component Deployment

Note that the UML can be used to model other processes besides software development.

1.4.1.1 Use Case diagram A typical interaction between a user and a computer system. 1.4.1.1.1

Figure 1.1: A sample UML Use Case Diagram.

1.4.1.2 Class diagram


Describes the types of objects in the system, and the static relationships between them. Two main kinds of static relationships: o Associations - Has-A o Subtypes - Is-A

1.4.1.2.1

Figure 1.2: A high level class diagram showing the relationships between classes.

1.4.1.2.2

Figure 1.3: A class diagram showing the detailed attributes and behaviors of a class.

1.4.1.2.3

Figure 1.4: A class diagram showing relationships to classes in other packages

1.4.1.3 Sequence diagram


Sequence diagrams follow the flow of entire use cases (emphasis on time ordering). One sequence diagram for the basic course and alternative courses for each of your use cases.

Figure 1.5: A sequence diagram follows the flow of an entire use case.

1.4.1.4 Collaboration diagram


Shows how critical objects collaborate within a use case. Similar to sequence diagrams. o Focus on key transactions. o Sequence diagrams follow the flow of entire use cases (emphasis on time ordering). o Collaboration diagrams add extra detail related to timing of messages.

Figure 1.6: A collaboration diagram shows how important objects collaborate within a use case.

1.4.1.5 Package diagram


Classes are arranged into logically-ordered packages. Package diagrams show relationships and dependencies between packages. Package diagrams are vital for large projects.

1.4.1.6 State diagram

Captures the lifecycle of one or more objects.

1.4.1.6.1

Figure 1.7: A state diagram captures the lifecycle of one or more objects.

1.4.1.7 Activity diagram


Advanced flowcharts. Swimlanes let you organize a set of activities according to who is performing them.

1.4.1.8 Component diagram


The implementation view of a system. Displays the organization and dependencies between software components.

1.4.1.9 Deployment diagram


The environment view of a system. Shows the physical relationships among software and hardware components. Each node represents some computational unit - usually a piece of hardware. Connections show communication paths. In practice probably not used very much, though most projects have a drawing that looks something like these.

1.5 Object Oriented Software Development

Larger processes/methodologies: o Rational Unified Process (RUP) o Object-Oriented Software Process (OOSP) o OPEN Process Lightweight/agile processes: o XP (Extreme Programming) o Cockburn's Crystal Family o Open Source o Highsmith's Adaptive Software Development o Scrum o Coad's Feature Driven Development o DSDM (Dynamic System Development Method)

Larger/heavier processes are typically built around the Unified Modeling Language, or UML.

1.5.1 Why have a process?


Create a product that users want. Make the process manageable and predictable. Capability Maturity Model (CMM) from the Carnegie-Mellon University Software Engineering Institute defines five levels of "maturity". Traditional development process: Waterfall (Analysis, Design, Code, Test). Spiral process (Risk Analysis/Systems Analysis/User Feedback, Design, Code, Test/User Feedback). Objectory - defines the four project phases of Inception, Elaboration, Construction, Transition. o Completion of each Objectory phase marks a major milestione. o Objectory uses iteration to make complex projects possible. The process defines ways to make iterative projects manageable. Model the system before developing it (in the same way an architect models a new facility before building it).

Figure 1.8: Steps of the Capability Maturity Model. 1.6 The Rational Unified Process (RUP) The Rational Unified Process formally consists of the following steps:

Inception - a discover phase, where an initial problem statement and functional requirements are created. Elaboration - the product vision and architecture are defined, construction cycles are planned.

Construction - the software is taken from an architectural baseline to the point where it is ready to make the transition to the user community. Transition - The software is turned into the hands of the user's community.

Figure 1.9: A high-level view of the Rational Unified Process. (Image courtesy of Rational Software.)

1.6.1 Inception phase The ``The Rational Unified Process, An Introduction''[9] specifies the following objectives, activities, and artifacts from an inception phase. 1.6.1.1 Objectives

Establish project's scope and boundary conditions. Determine the critical uses of the system. Exhibiting at least one candidate architecture against some of the primary scenarios. Estimating the overall cost and schedule for the entire project. Estimating potential risks.

1.6.1.2 Activities

Formulate the scope of the project. Plan and prepare the business case, including alternatives for risk management, staffing, project plan, and trade-offs between cost, schedule, and profitability. Develop a candidate architecture.

1.6.1.3 Artifacts

A vision document. A use-case model survey. An initial project glossary. An initial business case. An initial risk assessment. A project plan. Other possible items: o An initial use-case model. o An initial domain model. o One or more prototypes.

1.6.2 Elaboration The ``The Rational Unified Process, An Introduction''[9], specifies the following purpose, objectives, activities, and outcome from an elaboration phase. 1.6.2.1 Purpose

Analyze the problem domain. Establish a sound architecturla foundation. Develop the project plan. Eliminate the highest-risk elements.

1.6.2.2 Objectives

Define, validate, and baseline the architecture. Baseline the vision. Baseline a plan for the construction phase. Demonstrate that the baseline architecture will support the vision for a reasonable cost in a reasonable time, or not.

1.6.2.3 Activities

The vision is elaborated. The process, infrastructure, and development environment are elaborated. Processes, tools, and automation support are put into place. The architecture is elaborated and the components are selected.

1.6.2.4 Outcome/Deliverables

An 80% complete use-case model has been developed. Supplementary requirements are documented. A software architecture description is created. An executable architectural prototype is created. A revised risk list and business case are created. A development plan for the overall project is created. An updated development case is created, specifying the process to be used.

1.6.2.5 Other artifacts


Construction plan. Software prototypes. Risk identification and management plan. A test plan. A data dictionary. A preliminary user manual.

1.6.3 Construction phase The ``The Rational Unified Process, An Introduction''[9], specifies the following objectives, activities, and deliverables from a construction phase. 1.6.3.1 Objectives

Minimize development costs by optimizing resources and avoiding unnecessary scrap and rework. Achieving adequate quality as rapidly as practical. Achieving useful versions as rapidly as practical.

1.6.3.2 Activities

Resource management, resource control, process optimization.

Complete component development and testing. Assessment of product releases against acceptance criteria.

1.6.3.3 Deliverables

The software product integrated on the adequate platforms. User manuals. A description of the current release.

1.6.4 Transition The text ``The Rational Unified Process, An Introduction''[9], specifies the following purpose, objectives and activities from a transition phase. 1.6.4.1 Purpose

Transition the software to the user community. o Beta testing. o Parallel operation with any existing legacy system. o Conversions of operational databases. o Training of users. o Product rollout.

1.6.4.2 Objectives

Achieving user self-supportability. Achieving stakeholder buy-in that the deployed product is complete and consistent with the evaluation criteria of the vision. Achieving final product baseline as rapidly and cost-effectively as possible.

1.6.4.3 Activities

Deployment-specific engineering: o Cutover o Commercial packaging and production o Sales rollout o Field personnel training Tuning activities, bug-fixing, and enhancement for performance and usability. Assessing the deployment baseline against the vision and acceptance criteria.

1.7 A sample process The next several sections provide an outline of a sample object-oriented software development process. Specifically, this process is based on the text ``Use Case Driven Object Modeling with UML, A Practical Approach'' by Rosenberg and Scott[4]. This is a real process, based on the theory outlined in the Rational Unified Process. 1.7.1 Domain modeling First guess at domain objects. 1.7.1.1 What is a class?

A class is a template for creating objects. A class defines the attributes and behaviors an object will have. An object is a specific instance of a class. If an object has no attributes, is it really a valid object?

1.7.1.1.1 Attributes

A data variable with object scope. Examples: book attributes: title, author, publisher, ISBN The value of an object's attributes define its state. Attributes should not be accessible to entities outside the object. If an object has no attributes, is it really a valid object?

1.7.1.1.2 Behaviors

Method: a function with object scope. Methods can operate on that object's attributes. Defines the objects behaviors - how it does what it does. Methods define the objects responsibilities. If an object has no methods, is it really a valid object?

1.7.1.2 Discover classes


Work outward from data requirements to build a static model. Jump start with grammatical inspection: Make a quick pass through the available material, making lists of the nouns, verbs, and possessive phrases.

Nouns become classes. Noun phrases becomes class attributes. Verbs become operations (behaviors) and associations. Possessive phrases may indicate that nouns should be attributes rather than objects. Create this list of "class candidates". Best sources of classes: high-level problem statement, lower-level requirements, expert knowledge of the problem space. Go through the candidate classes and eliminate the items that are unnecessary (redundant or irrelevant) or incorrect (too vague, represent concepts outside the model).

1.7.1.2.1 Where else do classes come from?


Tangible things - cars, telemetry data, pressure sensors Roles - mother, teacher, politician, manager Events - interrupt, request Interactions - loan, meeting, intersection People - humans who carry out some function Places - areas set aside for people or things Things - physical objects, devices Organizations - formally organized collections of people Concepts - principles or ideas that are not tangible

1.7.1.3 Build generalization relationships


Generalization - one class is a refinement of another class. Define Is-a relationships. Break into (1) superclass/parent, and (2) subclass/child. Child inherits attributes and behaviors of the parent. Sometimes discover classes "ahead of schedule".

1.7.1.4 Build associations between classes


Association: A static relationship between two classes. Show dependencies between classes but not between actions. Should be a true statement about the problem space, independent of time (i.e., static). Build the list of candidate associations from the list of verbs and verb phrases and knowledge of the problem domain.

Examples:

Order generates Trade.

Portfolio places Orders. Posting involves GLAccount. Trade generates TradeLot. Some associations are one-to-one, some are one-to-many. These are referred to as multiplicities. Don't worry about being more specific about numbers of one-to-many associations at this time. Aggregation: an association in which one class is made up of other classes. "Has-a" or "part-of" relationships.

1.7.1.5 Mine legacy documentation for domain classes


Relational database tables are an excellent source of domain classes. Helper classes: contain attributes and operations that are relevant to more significant classes.

1.7.1.6 Wrapping up domain modeling 1.7.1.6.1 Continue to iterate and refine


Draw an analysis-level class diagram The user's wants and needs are the reason your project team exists. Establish a time budget for building your initial domain model. The diagram you draw during domain modeling is just a skeleton of your object model.

1.7.1.6.2 Three key principles


Work inward from user requirements. Work outward from data requirements. Drill down from high-level models to detailed design.

1.7.2 Use case modeling 1.7.2.1 Actors


An actor is anyone or anything that must interact with the system. An actor is not part of the system. Actors are typically found in the problem statement, and by conversations with customers and domain experts. Actors are drawn as a stick figures. When dealing with actors it is important to think about roles.

Questions to help identify actors


Who is interested in a certain requirement? Who installs the system? Who starts and stops the system? Where in the organization is the system used? Who will benefit from use of the system? Who will supply the system with this information, use this information, and remove this information? Who will support and maintain the system? Does the system use an external resource? Does one person play several different roles? Do several people play the same role? Does the system interact with a legacy system? What other systems use this system? Who gets information from this system?

1.7.2.1.1 Use Cases Use Case - a sequence of actions that an actor performs within a system to achieve a particular goal. The purpose of this stage is to capture user requirements of the new system using use case diagrams.

Definition: A sequence of actions that an actor performs within a system to achieve a particular goal. A use case describes one or more courses through a user operation. The basic course must always be present; alternate courses are optional. Basic course - the main start-to-finish path the user will follow under normal circumstances. Alternate course - infrequently used path, an exception, or an error condition. Stated from the perspective of the user as a present-tense verb phrase in an active voice (AdmitPatient, Do Trade Entry, Generate Reports). Describes one aspect of usage of the system without presuming any specific design or implementation. Ask "what happens?" "Then what happens?" Be relentless. All required system functionality should be described in the use cases. Actor - represents a role a user can play with regard to a system. A user can serve as more than one type of actor. Use cases appear as ovals, generally in the middle of a use case diagram. Analysis level and design level use cases.

Should be able to write a solid paragraph or two about a design-level use case. Use cases should have strong correlations with material in the user manual for the system (write the manual, then write the code). (Write the manual as though the system already exists.) Use rapid prototyping as frequently as possible. If you're reengineering an existing legacy system, work from the user manual backward. A use case captures some user-visible function. A use case achieves a discrete goal for the user. A use case may be large or small. Use cases model a dialogue between an actor and the system.

1.7.2.1.2 Questions to help identify use cases[11]


What are the tasks of each actor? Will any actor create, store, change, remove, or read information in the system? What use case will create, store, change, remove, or read this information? Will any actor need to inform the system about sudden, external changes? Does any actor need to be informed about certain occurrences in the system? What use cases will support and maintain the system? Can all functional requirements be performed by the use cases?

1.7.2.1.3 Use case diagrams


Use case diagrams identify use cases and actors of the system. Use case-actor relationships are shown with association lines. Use cases appear as ovals, generally in the middle of a diagram. Use cases appear at various levels of detail; two such levels are analysis-level and design-level.

Figure 1.10: A sample use case diagram.

1.7.2.1.4 Use case diagrams - include and extend


One use case can use or extend another use case. The secondary (sub-level) use case is not associated directly with an actor. Stereotypes includes - use/include a piece of behavior that is similar across more than one use case. extends - one use case is similar to another, but does more.

1.7.2.1.5 Wrapping Up Use Case Modeling Feel comfortable when you've achieved the following goals: 1. Your use cases account for all of the desired functionality of the system. 2. You have clear and concise descriptions of the basic course of action, with appropriate alternate courses of action. 3. You have factored out common scenarios. 1.7.2.1.6 Milestone 1: Requirements Review

1.7.3 Robustness analysis Robustness analysis involves: 1. analyzing the text of each of your use cases, 2. identify a first-guess set of objects that will participate in the use case, then 3. classify these objects into 1. Boundary objects 2. Entity objects 3. Control objects 4. This has parallels in the Model/View/Controller paradigm. 1.7.3.1 Definitions

Boundary objects - Actors use these to communicate with the system ("View"). Entity objects - Usually objects from the problem domain ("Model"). Control objects - Serve as the "glue" between Boundary and Entity objects ("Controller").

1.7.3.2 Key roles of robustness analysis


Sanity check - make sure your use case text is correct. Completeness check - make sure your use cases address all the necessary alternate courses of action. Ongoing discovery of objects - you may have missed some objects during domain modeling.

1.7.3.3 Closer look at object types 1.7.3.3.1 Boundary objects


"View". Objects that the Actors will be interacting with. Windows, screens, dialogs, menus. Get many from prototypes.

1.7.3.3.2 Entity objects


"Model". Often map to database tables and files. Many come from the domain model. Simpler and more generic - easier to reuse in other projects.

1.7.3.3.3 Control objects


"Controller". Embody much of the application logic. Where you capture business rules and application logic. Not necessarily meant to endure as stand-alone classes as you proceed. Sometimes serve as placeholders to make sure you don't forget any functionality and system behavior required by your uses cases.

1.7.3.4 Performing robustness analysis


Actors can talk only to Boundary objects. Boundary objects can talk only to Controllers and Actors. Entity objects can only talk to Controllers. Controllers can talk to both Boundary objects and Controllers, but not to Actors. Update your static model.

1.7.3.4.1 Milestone 2: Preliminary Design Review 1.7.4 Interaction modeling 1.7.4.1 Introduction Current state:

Uncovered most problem space objects and assigned some attributes to them. Defined some static relationships between these objects. Defined a few dynamic relationships on robustness diagrams.

Interaction modeling is the phase in which you build the threads that weave your objects together and enable you to see how they will perform useful behavior. One of the primary tools of this task is creating sequence diagrams. Objectives Upon completion of this section, students will be able to:

Define the goals of interaction modeling. Create sequence diagrams. Put behavioral methods on your classes.

Update your static model.

1.7.4.2 Goals of Interaction Modeling


Allocate behavior among entity, boundary, and control objects. Show detailed interactions that occur over time among objects. Finalize the distribution of operations among classes.

1.7.4.3 Sequence Diagrams


Represent the major work product of our design. Draw one sequence diagram that encompasses the basic course and all alternative courses within each of your use cases. One sequence diagram per use case. These results form the core of your dynamic model.

1.7.4.3.1 Four Sequence Diagram Elements


The text for the course of action of the use case. Objects. Messages. Methods (operations, behaviors).

1.7.4.4 Getting Started Four steps to creating diagrams:


Copy the use case text to the left margin of the sequence diagram. Add the entity objects. Add the boundary objects. Work through the controllers, one at a time. Determine how to allocate behavior between the collaborating objects.

1.7.4.5 Putting Methods on Classes


This is the essence of interaction modeling. It's also hard. A cow needs milking. Does the cow object milk itself, or does the Milk object "de-cow" itself? Convert controllers from robustness diagrams to sets of methods and messages that embody the desired behavior. An object should have a single "personality". Avoid schizophrenic objects. If you have objects with split personalities you should use aggregation.

Use CRC cards to help. Behavior allocation is of critical importance. Don't show message parameters on your sequence diagrams.

1.7.4.5.1 Which Methods Belong With Objects


Reusability - the more general, the more reusable. Does this method make the class more or less reusable. Applicability - is there a good fit between the object and method? Complexity - is it easier to build a method in another object? Implementation knowledge - does the implementation of the behavior depend on details internal to the associated method?

1.7.4.6 Completing Interaction Modeling


Drawn all needed sequence diagrams. Updated your static model. Last stop before you start coding; Critical Design Review is essential.

1.7.5 Collaboration and State Modeling 1.7.5.1 Introduction


Model additional aspects of your system. Most useful in real-time system design. Collaboration diagrams are similar to sequence diagrams.

1.7.5.2 Collaboration diagrams


Shows how critical objects collaborate within a use case. Collaboration diagrams are similar to sequence diagrams. o Collaboration diagrams focus on key transactions. o Sequence diagrams follow the flow of entire use cases (emphasis on time ordering). o Collaboration diagrams add extra detail related to timing of messages.

1.7.5.3 State diagrams


Captures the lifecycle of one or more objects. Expressed in terms of: o Different states objects can assume o Events that cause changes in state

Basic elements:

Initial state - hollow circle containing a black dot. Each additional state - rectangle with rounded corners. Three standard events: o Entry o Exit o Do Transition - an arrow between two states.

1.7.5.3.1 How many state diagrams are needed?

Every object has a state machine. o Object is created. o Sends messages. o Receives messages. o It is destroyed. In reality, most state machines are boring, so don't waste time drawing them. o Don't diagram an object with two states, On and Off. Readability is important.

1.7.5.4 Activity diagrams


Remarkably similar to flowcharts. Swimlanes - group a set of activities according to who is performing them. A good way to understand/model business processes.

1.7.6 Addressing Requirements 1.7.6.1 Introduction This section shows how to trace the results of your analysis and design work back to your user requirements. 1.7.6.2 Objectives Upon completion of this section, students will be able to:

Define a requirement Describe the nature of requirements, use cases, and functions

1.7.6.3 What is a Requirement?


A user-specified criterion that the system must satisfy. Requirements define the bahvior and functionality of a proposed system. Usually expressed as sentences that include the word shall or must.

1.7.6.3.1 Types of Requirements


Functional - ``The system shall automatically generate postings to the general ledger''. Data - ``The system ... international currencies ...''. Performance - ``The system must ... in XX seconds''. Capacity - ``Up to 10,000 transactions per day''. Test - ``Stress testing shall ... XX users ... YY computers ...''.

1.7.6.4 Use Cases and Requirements


A use case describes a unit of behavior. A requirement describes a law that governs behavior. Several types of requirements: functional, performance, and constraints. A use case can satisfy one or more functional requirements. A functional requirement may be satisfied by one or more use cases. Requirements are requirements, use cases are use cases. Requirements are not use cases.

1.7.6.5 Requirements Traceability


Make a list of the system requirements. Write the user manual for the system in the form of use cases. Iterate with your customers until you have closure of items 1 and 2. Make sure you can trace every piece of your design to at least one user requirement. Make sure you can trace every requirement to the point at which its satisfied within your design. Trace your design back to your requirements as you review the design during your critical design review.

1.7.7 Survey of Design Patterns

Repeating patterns - ``Her garden is like mine, except that in mine I use astilbe.''

Recurring solutions to design problems you see over and over. A set of rules describing how to accomplish certain tasks in the realm of software development. Made famous by the text ``Design Patterns'', by Gamma, Helm, et al. A list of some of the most well-known design patterns:
Factory Singleton Prototype Bridge Decorator Flyweight Chain of Responsibility Interpreter Mediator Observer Strategy Visitor Abstract Factory Builder Adapter Composite Facade Proxy Command Iterator Memento State Template

1.7.7.1 Factory pattern example

The code and diagram that follow demonstrate a small, simple example of the Factory pattern

public abstract class Dog { public abstract void speak (); } public class Poodle extends Dog { public void speak() {

System.out.println("The poodle says \"arf\""); } } public class SiberianHusky extends Dog { public void speak() { System.out.println("The husky says \"Whazzup?!!\""); } } public class Rottweiler extends Dog { public void speak() { System.out.println("The Rottweiler says (in a very deep voice) \"WOOF!\""); } } public class Main { public Main() { // create a small dog Dog dog = DogFactory.getDog("small"); dog.speak();

// create a big dog dog = DogFactory.getDog("big"); dog.speak(); // create a working dog dog = DogFactory.getDog("working"); dog.speak(); } public static void main(String[] args) { new Main(); } } public class DogFactory { public static Dog getDog(String criteria) { if ( criteria.equals("small") ) return new Poodle(); else if ( criteria.equals("big") ) return new Rottweiler(); else if ( criteria.equals("working") ) return new SiberianHusky(); return null; }

1.7.7.1.1

Figure 1.11: A UML use case diagram for the DogFactory.

1.8 Agile Methods Many developers believe that formal ``heavyweight'' processes like RUP still have significant shortcomings. According the original Extreme Programming text (the ``white book''), at a minimum the following roblems still exist:

Schedule slips Project canceled System goes sour Defect rate Business misunderstood Business changes

False feature rich Staff turnover

1.10 Introduction to Extreme Programming This is a simple introduction to Extreme Programming, taken largely from the text ``eXtreme Programming explained'' (the ``white book''). 1.10.1 Risk: The Basic Problem Quoting from the white book, ``the basic problem of software development is risk''. Here are some examples:

Schedule slips Project canceled System goes sour Defect rate Business misunderstood Business changes False feature rich Staff turnover

1.10.2 Four Variables In the XP model there are four control variables in software development: 1. 2. 3. 4. Cost Time Quality Scope

Customers and managers get to pick the values of any three of the variables. 1.10.3 The Cost of Change Under certain circumstances the exponential rise in the cost of changing software over time can be flattened. If the cost curve can be flattened, old assumptions about the best way to develop software no longer hold true. Several factors make code easy to change, even after years of production: 1. A simple design 2. Automated tests 3. Lots of practice in modifying the design

1.10.4 Four Values 1. 2. 3. 4. Communication Simplicity Feedback Courage

1.10.5 Basic Principles 1. 2. 3. 4. 5. Rapid Feedback Assume simplicity Incremental change Embracing change Quality work

1.10.6 Back to Basics 1. 2. 3. 4. Coding Testing Listening Designing

1.10.7 The Solution 1. The Planning Game Business people get to decide: Scope Priority 3. Composition 4. Dates of releases
1. 2.

Technical people get to decide: Estimates Consequences 3. Process 4. Detailed scheduling Small Releases Metaphor Simple Design Testing Refactoring
1. 2.

2. 3. 4. 5. 6.

7. Pair Programming 8. Collective Ownership 9. Continuous Integration 10. 40-Hour Week 11. On-Site Customer 12. Coding Standards 1.11 OO Summary This section provides a summary of our Day One activities. 1.11.1 OO Concepts Software concepts essential to object orientation:

Encapsulation - the grouping of related ideas into unit. Encapsulating attributes and behaviors. Inheritance - a class can inherit its behavior from a superclass (parent class) that it extends. Polymorphism - literally means ``many forms''. Information/implementation hiding - the use of encapsulation to keep implementation details from being externally visible. State retention - the set of values an object holds. Oject identity - an object can be identified and treated as a distinct entity. Message passing - the ability to send messages from one object to another. Classes - the templates/blueprints from which objects are created. Genericity - the construction of a class so that one or more of the classes it uses internally is supplied only at run time.

1.11.2 UML The UML defines nine standard diagrams: 1. Use Case 2. Class 3. Interaction 1. Sequence 2. Collaboration 4. Package 5. State 6. Activity

7. Deployment Rational Unified Process


Inception - a discover phase, where an initial problem statement and functional requirements are created. Elaboration - the product vision and architecture are defined, construction cycles are planned. Construction - the software is taken from an architectural baseline to the point where it is ready to make the transition to the user community. Transition - The software is turned into the hands of the user's community.

Agile Methods

Our highest priority is to satisfy the customer through early and continuous delivery of valuable software. Welcome changing requirements, even late in development. Agile processes harness change for the customer's competitive advantage. Deliver working software frequently, from a couple of weeks to a couple of months, with a preference to the shorter timescale. Business people and developers must work together daily throughout the project. Build projects around motivated individuals. Give them the environment and support they need, and trust them to get the job done. The most efficient and effective method of conveying information to and within a development team is face-to-face conversation. Working software is the primary measure of progress. Agile processes promote sustainable development. The sponsors, developers, and users should be able to maintain a constant pace indefinitely. Continuous attention to technical excellence and good design enhances agility. Simplicity-the art of maximizing the amount of work not done-is essential. The best architectures, requirements, and designs emerge from selforganizing teams. At regular intervals, the team reflects on how to become more effective, then tunes and adjusts its behavior accordingly.

Design Patterns

Repeating patterns - ``Her garden is like mine, except that in mine I use astilbe.'' Recurring solutions to design problems you see over and over. A set of rules describing how to accomplish certain tasks in the realm of software development. Made famous by the text ``Design Patterns'', by Gamma, Helm, et al.

The Genesis of Java Design Patterns


The idea of patterns and a pattern language was introduced by Christopher Alexander, a building architect as a means of applying certain solutions over and over again to the same or similar problems. He also combined these existing solutions to create new solutions to new problems. Later, Ward Cunningham and Kent Beck developed five patterns to use in interaction design and finally in 1994 Erich Gamma, Richard Helm, John Vlissides, and Ralph Johnson published the classic book Design Patterns: Elements of Reusable ObjectOriented Software, that documented patterns that has become a software industry standard. In 1999, with the introduction of Java 2 Enterprise Edition, Suns Java consulting practice in Sun Professional Services, realized that companies were not using the technology correctly and architecting solutions that were not scalable. It is within this context that John Crupi, Deepak Alur, and Danny Malks decided to document the appropriate patterns to successfully architect a JEE solution. This lead to the book, Core JEE Patterns: Best Practices and Design Strategies. We will describe how you can use patterns to help you create an architecture. Instead of using the pattern sat the object or class level, which is the custom, we will abstract them to a higher level. Initially we will focus on the Gang of Four (GoF) patterns, as described in the classic book, Design Patterns: Elements of Reusable Object-Oriented Software and then move on to the core JEE patterns, as described in the book, Core JEE Patterns, Crupi, et al. As an architect, we look for your knowledge of patterns to arrive at the following level: Be able to describe each of the Gang of Four design patterns Be able to describe each of the Core JEE patterns Categorize a pattern as a Core JEE pattern or GoF design pattern based on the name Understand the basics of applying patterns

Gang of Four Patterns


The GoF patterns are categorized into three categories, as follows: CreationalSupport the creation of objects StructuralDeal with relationships between portions of your application BehavioralInfluence how state and behavior flow through the system

Creational Patterns
Creational patterns are used to support the creation of objects in a system. They allow objects to be created in a system without needing to identify a specific class type in the code, thus avoiding the need to write large, complex code to instantiate an object. Creational patterns achieve this by leveraging the subclass of the class to create the objects. This may limit the type or number of objects that can be created within a system. The Creational patterns are Abstract Factory, Builder, Factory Method, Prototype, and Singleton.

Abstract Factory Pattern

The Abstract Factory pattern provides an interface for creating a family of related or dependent objects without specifying their concrete classes. Given a set of related abstract classes, the Abstract Factory pattern provides the means to create instances of these abstract classes from a matched set of concrete subclasses. The Abstract Factory pattern is shown in the figure below:.

Figure: Abstract Factory The Abstract Factory pattern uses an abstract class to determines the appropriate concrete class to instantiate in order to create a set of concrete products implementing a standard interface. The client only interacts with the product interfaces and the Abstract Factory class. The client never knows about the concrete construction classes provided in this pattern. This pattern is similar to the Factory Method pattern, except that it creates families of related objects. Benefits The benefits from using the Abstract Factory pattern are the following: Isolates the concrete classes from client Allows for exchanging product families easy Promotes consistency among products by implementing a common interface When to Use The Abstract Factory pattern should be applied in the following situations: When the system should be independent of how its products are created, composed, and represented. When the system needs to be configured with one of multiple families of products such as for Microsoft Windows , Linux or Apple OSX classes. When the family of related product objects are designed to be used together, and it is necessary to enforce this constraint. This is one of the key reasons for the existence of this pattern; otherwise, you could use a Factory Method. When you want to provide a class library of products and only reveal their interfaces, not their implementations.

Builder Pattern
The Builder pattern is used to separate the construction of a complex object from its representation in order that the same construction process can be use to create different objects. The Builder pattern allows the client object to construct a complex object by providing its type and content. The client is shielded from all the details of the objects construction. It simplifies the creation of complex objects by defining a class that is used to build instances of another class. The Builder pattern is often used to build product that are in accordance with the composite pattern. The figure illustrates the Builder pattern.

Figure:Builder Pattern The Builder pattern allows you to create the complex objects one step at a time. Other patterns can build the object in a single step. Benefits The benefits from using the Builder pattern are the following: It allows you to vary a products internal representation It isolates the code for construction and representation It gives you greater control over the construction process When to Use The Builder pattern should be applied in the following situations: When the algorithm for creating a complex object should be independent of both the parts that make up the object and how these parts are assembled. When the construction process must allow different representations of the constructed object.

Factory Method Pattern


The Factory Method pattern defines an interface for creating an object, but lets the subclasses determine which class to instantiate. The Factory Method allows a class to defer instantiation to subclasses. This is very is useful for constructing individual objects for a specific purpose without requiring the requestor to know the specific class being instantiated. This enables you to introduce new classes without the need to modify the code since the new class only implements the interface so it can be used by the client. The figure below shows the Factory Method pattern:

Figure: Factory Method Pattern Benefits The benefits from using the Factory Method pattern are the following:

It eliminates the need to bind application classes into your code. The code relates only to

the interface and you can work with any classes that implement the relevant interface. It enables subclasses to provide an extended version of an object, since it is more flexible to create an object inside a class than to create an object directly in the client. When to Use The Factory Method pattern should be applied in the following situations: When a class cannot anticipate the class of objects it must create. When a class wants its subclasses to specify the objects it creates. When classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.

Prototype Pattern
The Prototype pattern is used by an object to create objects by cloning an existing object. It does this without knowing their exact class or the details of how to create them. Instead it specifies the kinds of objects to create using a prototypical instance and then creates new objects by copying this prototype. The Prototype pattern works by giving prototypical objects to an object and then initiates the creation of objects. The object that initiates the target object creation by asking the prototypical objects to make copies of themselves. The Prototype pattern makes creating objects dynamically easier by defining classes whose objects can duplicate themselves. The Prototype pattern is shown in the figure below:

Figure:Prototype Pattern Benefits The benefits from using the Prototype pattern are the following: It can add and remove products at run time It specifies new objects by varying values It specifies new objects by varying structure It reduces subclasses It configures an application with classes dynamically When to Use The Prototype pattern should be applied in the following situations: When the classes to instantiate are specified at run time by dynamic loading for example. When its necessary to avoid building a class hierarchy of factories paralleling the class hierarchy of products When instances of a class can have one of only a few different combinations of state

Singleton Pattern
The Singleton pattern ensures that there is only one instance of a class and that provides a global point of access to the class. It ensures that all objects using an instance of this class use the same instance. The figure below shows the Singleton pattern:

Figure:Singleton Pattern Benefits The benefits from using the Singleton pattern are the following: It controlled access to sole instance It reduces the name space It permits refinement of operations and representation It permits a variable number of instances More flexible than class operations When to Use The Singleton pattern should be applied in the following situation: When there must be exactly one instance of a class.

Structural Patterns
Structural patterns deal with how classes and objects are composed into larger structures. Structural class patterns use inheritance in order to compose interfaces and implementations. They affect applications in a variety of ways. For example, the Adapter pattern enables two incompatible systems to communicate, and the Faade pattern enables one to present a simplified interface to a user without eliminating all the options available in the system. Structural patterns allow you to create systems without the need to rewrite or customize any code. This pattern allows for a system to have enhanced reusability and robust functionality. The structural patterns are Adapter, Bridge, Composite, Decorator, Faade, Flyweight, and Proxy.

Adapter Pattern
Adapter pattern acts as an intermediary between two classes, converting the interface of one class in order that it can be used with another. This pattern enables classes with incompatible interfaces to work together. The Adapter pattern allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class. It provides the functionality of an interface without having to know the class used to implement that interface. The figure below illustrates the Adapter pattern:

Figure:Adapter Pattern Benefits The benefits from using the Adaptor pattern are the following: It facilitates communication and interaction between two or more incompatible objects It improves the reusability of legacy functionality When to Use The Adaptor pattern should be applied in the following situation: When you want to use an existing class, and its interface does not match the interface you need. When you want to create a reusable class that cooperates with unrelated or unforeseen classesthat is, classes that dont necessarily have compatible interfaces. When you want to use an object in an environment that expects an interface that is different from the objects interface. When interface translation among multiple sources must occur.

Bridge Pattern
The Bridge pattern divides a complex component into two separate but related inheritance hierarchies: the functional abstraction and the internal implementation. This makes it easier to change either aspect of the component so that the two can vary independently. The Bridge pattern is useful when there is a hierarchy of abstractions and a corresponding hierarchy of implementations. Rather than combining the abstractions and implementations into many distinct classes, the Bridge pattern implements the abstractions and implementations as independent classes allowing them to be combined dynamically. The figure below shows the Bridge pattern:

Figure:Bridge Pattern Benefits The benefits from using the Bridge pattern are the following:

It enables you to separate the interface from the implementation It improves extensibility It hides implementation details from clients
When to Use The Bridge pattern should be applied in the following situation: When you want to avoid a permanent binding between an abstraction and its implementation. When both the abstractions and their implementations should be extensible using subclasses. When changes in the implementation of an abstraction should have no impact on clients; that is, you should not have to recompile their code.

Composite Pattern
The Composite pattern composes one-or-more similar objects such that they can be manipulated as one object. It enables you to create hierarchical tree structures of varying complexity, while also allowing every element in the structure to operate with a uniform interface. The Composite pattern combines objects into tree structures representing either the whole hierarchy or a part of the hierarchy allowing clients to treat individual objects and compositions of objects uniformly. The figure below illustrates the Composite pattern:

Figure:Composite Pattern Benefits The benefits from using the Composite pattern are the following: Defines class hierarchies consisting of primitive objects and composite objects Makes it easier to add new kinds of components Provides flexibility of structure and a manageable interface When to Use The Composite pattern should be applied in the following situation: When you want to represent the whole hierarchy or a part of the hierarchy of objects. When you want clients to be able to ignore the difference between compositions of objects and individual objects. When the structure can have any level of complexity and is dynamic.

Decorator Pattern
The Decorator pattern enables you to dynamically add or remove object functionality without changing

the external appearance or function of the object. It changes the functionality of an object in a manner transparent to its clients by using an instance of a subclass of the original class to delegate operations to the original object. The Decorator pattern attaches additional responsibilities to an object dynamically to provide a flexible alternative to changing object functionality without using static inheritance. The figure below illustrates the Decorator pattern:

Figure:Decorator Pattern Benefits The benefits from using the Decorator pattern are the following: It has more flexibility than static inheritance It avoids feature-laden classes high up in the hierarchy It simplifies coding because you write a series of classes, each targeted at a specific part of the functionality, rather than coding all behavior into the object It enhances the objects extensibility because you make changes by coding new classes When to Use The Decorator pattern should be applied in the following situation: When you want to add responsibilities to individual objects dynamically and transparently without affecting other objects. When you want to add responsibilities to the object that you might want to change in the future. When extension by static subclassing is impractical.

Faade Pattern
The Faade pattern provides a unified interface to a group of interfaces in a subsystem. The Faade pattern defines a higher-level interface that makes the subsystem easier to use since there is only one interface instead of many. This unified interface enables an object to access the subsystem using the interface to communicate with the subsystem. The figure below illustrates the Faade pattern:

Figure:Facade Pattern Benefits The benefits from using the Facade pattern are the following: It provides a simple interface to a complex system without reducing the options provided by the system It shields clients from subsystem components It promotes weak coupling between the subsystem and its clients It reduces coupling between subsystems if every subsystem uses its own Faade pattern and other parts of the system use the Faade pattern to communicate with the subsystem It translates the client requests to the subsystems that can fulfill those requests When to Use The Facade pattern should be applied in the following situation: You want to provide a simple interface to a complex subsystem. There are many dependencies between clients and the implementation classes of an abstraction. You want to layer your subsystems.

Flyweight Pattern
The Flyweight pattern reduces the number of low-level, detailed objects within a system by sharing objects. If instances of a class that contain the same information can be used interchangeably, the Flyweight pattern allows a program to avoid the expense of multiple instances that contain the same information by sharing one instance. The figure below illustrates the Flyweight pattern.

Figure:Flyweight Pattern Benefits The benefits from using the Flyweight pattern are the following: It reduces in the number of objects to handle It reduces in memory and on storage devices, if the objects are persisted When to Use The Flyweight pattern should be applied in the following situation: When the application uses a large number of objects. When storage costs are high because of the quantity of objects. When the application doesnt depend on object identity.

Proxy Pattern
The Proxy pattern provides a surrogate or placeholder object to control access to the original object. There are several types of implementations of the Proxy pattern, with the Remote proxy and Virtual proxy being the most common. The figure below illustrates the Proxy pattern.

Figure:Proxy Pattern Benefits The benefits from using the Proxy pattern are the following: It allows remote proxies to hide an object resides in a different address space. It allows virtual proxies to perform optimizations, such as creating an object on demand.

When to Use The Proxy pattern should be applied in the following situation: When you need a more versatile or sophisticated reference to an object than a simple pointer.

Behavioral Patterns
Behavioral patterns focus on algorithms and the assignments of responsibilities between objects. These patterns shape the patterns of communication and characterize complex control flow through a system. By optimizing how state and behavior are transferred and modified, you can simplify, optimize, and increase the maintainability of an application. The Behavioral patterns are Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, and Visitor

Chain of Responsibility Pattern


The Chain of Responsibility pattern provides for loose coupling. It establishes a chain within a system, so that a message can either be handled at the level where it is first received, or be directed to an object that can handle it. The figure below illustrates the Chain of Responsibility pattern.

Figure:Chain of Responsibility Benefits The benefits from using the Chain of Responsibility pattern are the following: It reduces coupling It increases flexibility in assigning responsibilities to objects It allows a set of classes to behave as a whole, because events produced in one class can be sent on to other handler classes within the composite When to Use The Chain of Responsibility pattern should be applied in the following situation: When more than one object can handle a request, and the handler isnt known. When you want to issue a request to one of several objects without specifying the receiver explicitly. When the set of objects that can handle a request should be specified dynamically.

Command Pattern

The Command pattern encapsulates a request in an object, which enables you to store the command, pass the command to a method, and return the command like any other object. The figure below illustrates the Command pattern.

Figure:Command Pattern Benefits The benefits from using the Command pattern are the following: It separates the object that invokes the operation from the one that knows how to perform it. Its easy to add new commands, because you dont have to change existing classes. When to Use The Command pattern should be applied in the following situation: When you want to parameterize objects by an action to perform. When you specify, queue, and execute requests at different times. When you must support undo, logging, or transactions.

Interpreter Pattern
The Interpreter pattern interprets a language to define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. The figure below illustrates the Interpreter pattern.

Figure:Interpreter Pattern Benefits The benefits from using the Interpreter pattern are the following:

Its easy to change and extend the grammar. The implementation of the grammar is easy.
When to Use The Interpreter pattern should be applied in the following situation: When the grammar of the language is simple. When efficiency is not a critical concern.

Iterator Pattern
The Iterator pattern provides a consistent way to sequentially access items in a collection that is independent of and separate from the underlying collection. The figure below illustrates the Iterator pattern.

Figure:Iterator Pattern Benefits The benefits from using the Iterator pattern are the following: It supports variations in the traversal of a collection It simplifies the interface of the collection When to Use The Iterator pattern should be applied in the following situation: When accessing collection objects contents without exposing its internal representation When support of multiple traversals of objects in a collection In order to provide a uniform interface for traversing different structures in a collection

Mediator Pattern
The Mediator pattern simplifies communication among objects in a system by introducing a single object that manages message distribution among other objects. The Mediator pattern promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. The figure below illustrates the Mediator pattern.

Figure:Mediator Pattern Benefits The benefits from using the Mediator pattern are the following: It decouples colleagues It simplifies object protocols It centralizes control The individual components become simpler and easier to manage since they no longer need to directly pass messages to each other. Components are more generic, because they no longer need to contain logic to deal with their communication with other components. When to Use The Mediator pattern should be applied in the following situation: When a set of objects communicate in well-defined but complex ways. When you want to customize a behavior thats distributed between several objects without using subclasses.

Memento Pattern
The Memento pattern preserves a snapshot of an objects state, so that the object can return to its original state without having to reveal its content to the rest of the world. The figure below illustrates the Memento pattern.

Figure:Memento Pattern Benefits The benefits from using the Memento pattern are the following: It preserves encapsulation boundaries It simplifies the originator When to Use The Memento pattern should be applied in the following situation: When a snapshot of an objects state must be saved so that it can be restored to that state later.

When using a direct interface to obtain the state would expose implementation details and
break the objects encapsulation.

Observer Pattern
The Observer pattern provides a way for a component to flexibly broadcast messages to interested receivers. It defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. The figure below illustrates the Observer pattern.

Figure:Observer Pattern Benefits The benefits from using the Observor pattern are the following: It abstracts coupling between subject and observer It supports for broadcast communication When to Use The Observor pattern should be applied in the following situation: When a change to one object requires changing the other object, and you dont know how many objects need to change. When an object should be able to notify other objects without making assumptions about the identity of those objects.

State Pattern
The State pattern allows an object to alter its behavior when its internal state changes. The object appears to change its class. The figure below illustrates the State pattern.

Figure:State Pattern

Benefits The benefits from using the State pattern are the following: It localizes state-specific behavior and partitions behavior for different states It makes state transitions explicit When to Use The State pattern should be applied in the following situation: When an objects behavior depends on its state, and it must change its behavior at runtime depending on that state. When operations have large, multipart conditional statements that depend on the objects state.

Strategy Pattern
The Strategy pattern defines a group of classes that represent a set of possible behaviors. These behaviors can then be used in an application to change its functionality. The figure below illustrates the Strategy pattern.

Figure:Strategy Pattern Benefits The benefits from using the Strategy pattern are the following: It provides an alternative to subclassing It defines each behavior in its own class, which eliminates conditional statements Its easier to extend a model to incorporate new behaviors without recoding the application When to Use The Strategy pattern should be applied in the following situation: When many related classes differ only in their behavior. When you need different variants of an algorithm. When an algorithm uses data unknown to clients.

Template Method Pattern


The Template Method pattern provides a method that allows subclasses to override parts of the method without rewriting it. Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. The Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithms structure. The figure below illustrates the Template Method pattern.

Figure:Template Method Benefits The benefits from using the Template Method pattern are the following: It is a fundamental technique for reusing code When to Use The Template Method pattern should be applied in the following situation: When you want to implement the invariant parts of an algorithm once and use subclasses to implement the behavior that can vary. When common behavior among subclasses should be factored and localized in a common class to avoid code duplication.

Visitor Pattern
The Visitor pattern provides a maintainable, easy way to represent an operation to be performed on the elements of an object structure. The Visitor pattern lets you define a new operation without changing the classes of the elements on which it operates. The figure below illustrates the Visitor pattern.

Figure:Visitor Pattern Benefits The benefits from using the Visitor pattern are the following: It makes adding new operations easy It gathers related operations and separates unrelated ones When to Use The Visitor pattern should be applied in the following situation: When an object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes. When classes defining the object structure rarely change, but you often want to define new operations over the structure.

Design Patterns Applied - Java EE Patterns


The Core JEE patterns are widely used in organizations architecting Java EE systems. They were the result of the experiences and a knowledge base which had built up around the use of a Java EE platform. After the initial set of patterns were developed, a new set of patterns were added when Java EE was extended to cover web services. There are also a number of patterns that have become obsolete with new technologies introduced in Java EE 5.

Presentation Tier
Presentation tier patterns are used to organize components for improving re-use when presenting data to the client tier. It is not required to apply all of these patterns in the presentation tier as some of the patterns overlap in providing a similar solution to a common problem.

Intercepting Filter

The Intercepting Filter pattern provides the ability to manipulate a request prior to processing or to manipulate the response before sending the results of the request. The figure below illustrates the Intercepting Filter pattern.

Figure:Intercepting Filter Patterns Benefits The benefits from using the Intercepting Filter pattern are the following: It centralizes pre-processing of requests It centralizes post-processing of responses When to Use The Intercepting Filter pattern should be applied in the following situation: When you need to pre-process a request or response. When you need to post-process a request or response.

Context Object
The Context Object pattern is used to encapsulate the specifics of protocol implementation to be shared. The figure below illustrates the Context Object pattern.

Figure:Context Object Pattern Benefits The benefits from using the Context Object pattern are the following:

It improves reusability and maintainability It allows code to be portable across operating systems
When to Use The Context Object pattern should be applied in the following situation: When components need access to system information In order to decouple application from underlining protocols and system interfaces

Front Controller
The Front Controller pattern creates central control logic for presentation request handling. The Front Controller is different from the Intercepting Filter in that the Front Controller is determining processing based on the request and an Intercepting Filter is modifying the request. The figure below illustrates the Front Controller pattern.

Figure:Front Controller Pattern Benefits The benefits from using the Front Controller pattern are the following: It centralizes control logic It improves reusability It improves separation of concerns When to Use The Front Controller pattern should be applied in the following situation: When you apply common logic to multiple requests In order to separate processing logic from view

Application Controller
The Application Controller pattern is used to centralize retrieval and invocation of request-processing components, such as commands and views. The figure below illustrates the Application Controller.

Figure:Application Controller Pattern Benefits The benefits from using the Application Controller pattern are the following: It improves extensibility It improves separation of concerns When to Use The Application Controller pattern should be applied in the following situation: In order to apply common control logic When you have centralized view management

View Helper
The View Helper pattern separates the processing logic from the view. The figure below illustrates the View Helper pattern.

Figure:View Helper Pattern Benefits The benefits from using the View Helper pattern are the following: It separates logic from the view When to Use The View Helper pattern should be applied in the following situation: In order to encapsulate view-processing logic

Composite View
The Composite View pattern combines simple views into a more complex view without handling the content or layout. The figure below illustrates the Composite View pattern.

Figure:Composite View Pattern Benefits The benefits from using the Composite View pattern are the following: It code duplication is reduced because you can create common headers, footers, and other components. It views can be changed based on access authorization. When to Use The Composite View pattern should be applied in the following situation: When you want common view components. When you view component changes based on authorization.

Dispatcher View
The Dispatcher View pattern handles the request and generates a response while managing limited business processing. The figure below illustrates the Dispatcher View pattern.

Figure:Dispatcher View Pattern Benefits The benefits from using the Dispatcher View pattern are the following: It separates processing logic from view It improves reusability

When to Use The Dispatcher View pattern should be applied in the following situation: When you have static views. When you have limited business processing.

Service to Worker
The Service to Worker pattern performs request handling and invokes business logic before control is passed to the view. The figure below illustrates the Service to Worker pattern.

Figure:Service to Worker Pattern Benefits The benefits from using the Service to Worker pattern are the following: It improves separation of concerns When to Use The Service to Worker pattern should be applied in the following situation: In order to centralize business logic for requests

Business Tier
Business tier patterns create a loose coupling among the business logic, presentation, and resources.

Business Delegate
The Business Delegate pattern hides the complexity of remote communication with business components from the client. The figure below illustrates the Business Delegate pattern.

Figure:Business Delegate Pattern Benefits The benefits from using the Business Delegate pattern are the following: It minimizes coupling of clients to business services It hides remoteness It improves performance When to Use The Business Delegate pattern should be applied in the following situation: When you want to encapsulate access to business services from multiple client types In order to translate exceptions into application exceptions Hide details of service creation

Service Locator
The Service Locator pattern uses a consistent approach to locating business components regardless of the type of components. The figure below illustrates the Service Locator pattern.

Figure:Service Locator Pattern Benefits The benefits from using the Service Locator pattern are the following: It standardizes the approach to retrieving business components When to Use The Service Locator pattern should be applied in the following situation:

When you have many different business services that are located in different ways.

Session Faade
The Session Faade pattern provides a coarse-grained service of business components to remote clients. This is the same as a Faade pattern, but just provides an interface to a service instead of code. The figure below illustrates the Session Faade pattern.

Figure:Session Facade Pattern Benefits The benefits from using the Session Facade pattern are the following: It reduces the number of calls to the business component from the client It reduces coupling between the tiers It improves performance by reducing fine-grained calls from client It provides a cleaner API to the client When to Use The Session Facade pattern should be applied in the following situation: When you have a series of calls to make to business components from the client.

Application Service
The Application Service pattern centralizes and aggregates business components. An application service could be thought of as a helper to the Session Faade that takes care of all the business logic and workflow. The figure below illustrates the Application Service pattern.

Figure:Application Service Pattern Benefits The benefits from using the Application Service pattern are the following: It centralizes and improves reusability of business logic It simplifies the Session Faade by eliminating the business logic

When to Use The Application Service pattern should be applied in the following situation: In order to start to see duplicated business logic in the Session Faade

Business Object
The Business Object pattern separates business data from logic. The figure below illustrates the Business Object pattern.

Figure:Business Object Pattern Benefits The benefits from using the Business Object pattern are the following: It separates persistence from business logic. When to Use The Business Object pattern should be applied in the following situation: When you want to increase reusability of business logic.

Composite Entity
The Composite Entity pattern aggregates business entities into a coarsegrained entity. The figure below illustrates the Composite Entity pattern. Benefits The following lists the benefits of using the Composite Entity pattern: It increases maintainability It improves network performance

Figure:Composite Entity Patterns

When to Use The Composite Entity pattern should be applied in the following situation: In order to avoid remote entity beans In order to leverage bean managed persistence (BMP) with custom persistence implementation In order to encapsulate POJO business objects

Transfer Object
The Transfer Object pattern uses an object to carry data across tiers. The figure below illustrates the Transfer Object pattern.

Figure:Transfer Object Pattern Benefits The benefits from using the Transfer Object pattern are the following: It reduces network traffic It reduces code duplication

When to Use The Transfer Object pattern should be applied in the following situation: You need to send objects between tiers.

Transfer Object Assembler


The Transfer Object Assembler pattern builds a composite transfer object and returns to the client. The figure below illustrates the Transfer Object Assembler.

Figure:Transfer Object Assembler Pattern Benefits The benefits from using the Transfer Object Assembler pattern are the following: It improves network performance When to Use The Transfer Object Assembler pattern should be applied in the following situation: When you have several transfer objects that are sent between tiers.

Value List Handler


The Value List Handler pattern caches results and allows the client to traverse and select from the results. The figure below illustrates the Value List Handler pattern.

Figure:Value List Handler Pattern Benefits The benefits from using the Value List Handler pattern are the following: It caches search results

It improves network performance It improves separation of concerns


When to Use The Value List Handler pattern should be applied in the following situation: When one desires to iterate through a set of objects. When one implements read-only lists without transactions.

Integration Tier
Integration tier patterns serve to isolate the core business logic of a system from all external legacy or new systems including various data stores.

Data Access Object


The Data Access Object pattern encapsulates access to a persistent store by managing the connection with the data store. The figure below illustrates the Data Access Object pattern.

Figure:Data Access Object Patterns Benefits The benefits from using the Data Access Object pattern are the following: It reduces code complexity in client It improves code reuse It provides easier migration to new data store When to Use The Data Access Object pattern should be applied in the following situation: In order to decouple data access from the business logic In order to provide all data access from a separate layer

Service Activator
The Service Activator pattern handles asynchronous requests to business components. The figure below illustrates the Service Activator pattern.

Figure:Service Activator Benefits The benefits from using the Service Activator pattern are the following: It allows the client to continue processing It integrates JMS into application When to Use The Service Activator pattern should be applied in the following situation: When you need to invoke a business service in an asynchronous manner.

Domain Store
The Domain Store pattern separates the persistence of an object from the object model. This pattern really became relevant with the advent of object relational model frameworks and products. You would use the domain store and data access object at the same time. The figure below illustrates the Domain Store pattern.

Figure:Domain Store Pattern Benefits The benefits from using the Domain Store pattern are the following: It decouples business logic from persistence logic When to Use The Domain Store pattern should be applied in the following situation: When you do not want to use entity beans. When the object model uses are complex.

Web Service Broker


The Web Service Broker pattern exposes and brokers services using XML and web protocols. The figure below illustrates the Web Service Broker pattern.

Figure:Web Service Broker Pattern Benefits The benefits from using the Web Service Broker pattern are the following: It exposes existing services to web When to Use The Web Service Broker pattern should be applied in the following situation: Need to expose services as web services

Summary
When applying the patterns from the catalog we have presented, developers need to consider a wide array of design issues affecting numerous aspects of the system. This includes security, data integrity, manageability, and scalability. The majority of these design issues could also be captured in pattern form, but we were focused on a lower level of abstraction than what we be needed to address those issues. it is on top of these abstractions that you will formulate the design patterns necessary to address these issues. Overall, the purpose here is to help you avoid making problematic choices that could lead to costly and difficult problems to address. That is the purpose of java design patterns. To make this process easier. We are now on to the last two articles in order to prepare you for the architecture exam. The next article will be on security. See you then.

Attached Thumbnails

MVC
The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating MVC-based Web applications. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Formsbased applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in theSystem.Web.Mvc namespace and is a fundamental, supported part of the System.Web namespace. MVC is a standard design pattern that many developers are familiar with. Some types of Web applications will benefit from the MVC framework. Others will continue to use the traditional ASP.NET application pattern that is based on Web Forms and postbacks. Other types of Web applications will combine the two approaches; neither approach excludes the other. The MVC framework includes the following components:

Figure 01: Invoking a controller action that expects a parameter value (Click to view full-size image) Models. Model objects are the parts of the application that implement the logic for the application s data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in SQL Server.

In small applications, the model is often a conceptual separation instead of a physical one. For example, if the application only reads a data set and sends it to the view, the application does not have a physical model layer and associated classes. In that case, the data set takes on the role of a model object.

Views. Views are the components that display the application s user interface (UI). Typically, this UI is created from the model data. An example would be an edit view of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Products object.

Controllers. Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn queries the database by using the values. The MVC pattern helps you create applications that separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The pattern specifies where each kind of logic should be located in the application. The UI logic belongs in the view. Input logic belongs in the controller. Business logic belongs in the model. This separation helps you manage complexity when you build an application, because it enables you to focus on one aspect of the implementation at a time. For example, you can focus on the view without depending on the business logic. In addition to managing complexity, the MVC pattern makes it easier to test applications than it is to test a Web Forms-based ASP.NET Web application. For example, in a Web Forms-based ASP.NET Web application, a single class is used both to display output and to respond to user input. Writing automated tests for Web Forms-based ASP.NET applications can be complex, because to test an individual page, you must instantiate the page class, all its child controls, and additional dependent classes in the application. Because so many classes are instantiated to run the page, it can be hard to write tests that focus exclusively on individual parts of the application. Tests for Web Forms-based ASP.NET applications can therefore be more difficult to implement than tests in an MVC application. Moreover, tests in a Web Forms-based ASP.NET application require a Web server. The MVC framework decouples the components and makes heavy use of interfaces, which makes it possible to test individual components in isolation from the rest of the framework. The loose coupling between the three main components of an MVC application also promotes parallel development. For instance, one developer can work on the view, a second developer can work on the controller logic, and a third developer can focus on the business logic in the model.

Deciding When to Create an MVC Application


You must consider carefully whether to implement a Web application by using either the ASP.NET MVC framework or the ASP.NET Web Forms model. The MVC framework does not replace the Web Forms model; you can use either framework for Web applications. (If you have existing Web Forms-based applications, these continue to work exactly as they always have.) Before you decide to use the MVC framework or the Web Forms model for a specific Web site, weigh the advantages of each approach.

Advantages of an MVC-Based Web Application


The ASP.NET MVC framework offers the following advantages:

It makes it easier to manage complexity by dividing an application into the model, the view, and the controller. It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application. It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure. For more information, seeFront Controller on the MSDN Web site.

It provides better support for test-driven development (TDD).

It works well for Web applications that are supported by large teams of developers and Web designers who need a high degree of control over the application behavior.

Advantages of a Web Forms-Based Web Application


The Web Forms-based framework offers the following advantages:

It supports an event model that preserves state over HTTP, which benefits line-of-business Web application development. The Web Forms-based application provides dozens of events that are supported in hundreds of server controls.

It uses a Page Controller pattern that adds functionality to individual pages. For more information, see Page Controller on the MSDN Web site. It uses view state or server-based forms, which can make managing state information easier.

It works well for small teams of Web developers and designers who want to take advantage of the large number of components available for rapid application development. In general, it is less complex for application development, because the components (the Page class, controls, and so on) are tightly integrated and usually require less code than the MVC model.

Features of the ASP.NET MVC Framework


The ASP.NET MVC framework provides the following features:

Separation of application tasks (input logic, business logic, and UI logic), testability, and testdriven development (TDD) by default. All core contracts in the MVC framework are interface-based and can be tested by using mock objects, which are simulated objects that imitate the behavior of actual objects in the application. You can unit-test the application without having to run the controllers in an ASP.NET process, which makes unit testing fast and flexible. You can use any unit-testing framework that is compatible with the .NET Framework.

An extensible and pluggable framework. The components of the ASP.NET MVC framework are designed so that they can be easily replaced or customized. You can plug in your own view engine, URL routing policy, action-method parameter serialization, and other components. The ASP.NET MVC framework also supports the use of Dependency Injection (DI) and Inversion of Control (IOC) container models. DI allows you to inject objects into a class, instead of relying on the class to create the object itself. IOC specifies that if an object requires another object, the first objects should get the second object from an outside source such as a configuration file. This makes testing easier.

A powerful URL-mapping component that lets you build applications that have comprehensible and searchable URLs. URLs do not have to include file-name extensions, and are designed to support URL naming patterns that work well for search engine optimization (SEO) and representational state transfer (REST) addressing.

Support for using the markup in existing ASP.NET page (.aspx files), user control (.ascx files), and master page (.master files) markup files as view templates. You can use existing ASP.NET features with the ASP.NET MVC framework, such as nested master pages, in-line expressions (< %= %>), declarative server controls, templates, data-binding, localization, and so on.

Support for existing ASP.NET features. ASP.NET MVC lets you use features such as forms authentication and Windows authentication, URL authorization, membership and roles, output and

data caching, session and profile state management, health monitoring, the configuration system, and the provider architecture.

Intro OOP - A term that should flow in your blood if you have to be a good programmer. It is an essential perspective, visualization and an art to understand the concept as a whole. OOP concepts redefine our thoughts(in programming paradigm) and the way we code. The concepts are very easy in theory, but a bit difficult to grasp in real world scenarios. And once you master this perspective, coding in any language would be a piece of cake. So lets get to the basics first(Mind you, the theory is really simple. Its gets confusing when you try to implement these concepts) OOP I guess its high time that I mention what OOP is all about. OOP - Object Oriented Programming, is a programming paradigm using "objects" data structures consisting of data fields and methods together with their interactions to design applications and computer programs. - Wikipedia Got any idea? Bet you haven't. Let me put it into simple words. Object Oriented Programming is a way to code, its an approach towards coding, its an approach to problem solving, is a real life simulation of programming methodology Ring any bells? Well, you will be the end of this tutorial(Or atleast the next!) Now that I have said OOP is an approach to programming, there are a few core concepts that make up this methodology. I am not listing them down at one go, instead I'll be explaining it one by one. Please note that these concepts are applicable for most of the programming languages. This tutorial explains these concepts with respect to real life scenario. Classes and Object What is the difference between C and C++? C++ is C with classes! So now what are Classes? Classes are a combination of related attributes(variables, properties) and functions. Going to a real life scenario, it would look like the following.

Car, Bike and Auto-rickshaw all have a set of properties and functions(methods). So these would constitute the concept of classes. It would have the variables Wheels, Doors, Colors etc. and a few set a functions like Steer, Accelerate, Brake etc. To go a bit into the coding part, the class car would look like this class Car { int wheel; int door; string color; steer() { .. Function description .. } accelerate() { .. Function description .. } brake() { .. Function description .. } } This would how a sample class would look. So now on to the next term, Objects. What is an Object? An Object is simply an instance of this class. For example, BMW X5 would be an object of class Car. I don't think more explanation on this is required, please leave a comment if you feel it is required. Data Abstraction Tough word? Nah, not really! Its an easy concept. Data Abstraction means you hide data(keep data abstract) from the user. Or in other words, only essential information are exposed to a user. There is a popular example for data abstraction. When you drive a car, to shift gears, all you have to do is move the Gear stick. You don't have to know how the bearings are working in the background. Similarly which building an application, you need not show unnecessary details to the user. Keep it simple! Data Encapsulation You already know this concept. No? Data Encapsulation can be defined as Wrapping up of Data and related functions. That was what we exactly did above in Classes and Objects. The properties(data) and

their related functions are combined into a single entity called Class. Inheritance This concept takes the literal meaning of Inheritance. Certain properties are inherited to us from our parents. This perspective is brought onto the programming methodology. I would explain this concept with the above example of Cars and Bikes. These classes share some common properties and functions, like Wheels, Doors, Color etc. So why not put these into a parent class called Vehicles and inherit these properties with specific values in each class? That's exactly what happens here. You write a class called Vehicle which would look like this class Vehicle { int wheels; int doors; string colors; steer(); accelerate(); brake(); } Note that you won't give the description for the functions over here, as each class(Car or Bike) have their own methods to Steer or Accelerate. Now if you write the class as class Car extends Vehicle (This is the Java syntax, might vary for other languages) { ...Class description... }

This class would have all the above mentioned properties, and can set their own values here. The hierarchy would look like shown in the image Polymorphism Don't get strangled by the name, its a simple concept. It's a concept which we can interpret a function in more than one way. To give an example, suppose a function to calculate the Area of a geometric figure(Circle, Square etc.). Ideally, one would create separate functions with different names for the figures. Using the concept of Polymorphism, you can have the same name for the function, yet do different functions with it. You will get used to this concept at a later point of time, so I'm not going into its depth now. Messaging Messaging is the core concept of communication among classes. To give an idea of it, let me put up a scenario. Suppose we have two classes, Driver and Car. The Driver has to communicate with the Car to do functions like accelerate, brake etc. So how is this interaction done? Yes, Car has a function accelerate, but some message should be sent from Driver to Carright? That's exactly what messaging is all about. Once you get into this, you would be doing Messaging every now and then. Conclusion Finally! Make sure that you are used to all these concepts. In the upcoming tutorials, you would be

seeing these concepts implemented in a real life scenario. Before ending up, let me note down the points to remember. OOP Concepts Classes and Objects Data abstraction Data encapsulation Inheritance Polymorphism Messaging Let me know if I have to add something to this tutorial! And if you are reading this, thanks for your patience.

You might also like