max 2006 flex best practices: applying design patterns and architecture

45
2006 Adobe Systems Incorporated. All Rights Reserved. 1 MAX 2006 Flex Best Practices: Applying Design Patterns and Architecture Joe Berkovitz Chief Architect, Allurent Inc.

Upload: orde

Post on 12-Feb-2016

31 views

Category:

Documents


0 download

DESCRIPTION

MAX 2006 Flex Best Practices: Applying Design Patterns and Architecture. Joe Berkovitz Chief Architect, Allurent Inc. Resources and Updates. The latest version of this presentation and all sample code is available at: http://joeberkovitz.com/max2006/. Background. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 1

MAX 2006 Flex Best Practices: Applying Design Patterns and ArchitectureJoe BerkovitzChief Architect, Allurent Inc.

Page 2: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 2

Resources and Updates

The latest version of this presentation and all sample code is available at:

http://joeberkovitz.com/max2006/

Page 3: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 3

25+ years developing user-facing software Started in scientific data visualization and

manipulation Educational applications for K-6 ATG: the web application explosion contributor to Java Server Faces currently Chief Architect at Allurent, Inc.

Background

Page 4: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 4

Overview

Why use architecture and patterns? What we want from a "well-built" Flex application A specific example: ReviewTube MVCS: A useful division of labor in the client Dealing with asynchronous communication Guidelines and tips for view construction Principles and recipes

Page 5: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 5

What Is Software Architecture?

Ideas that give “mental traction” on building, understanding

Broad solutions to large problems Themes that shape solutions to many small problems Breaking up a complex system into simpler ones with…

responsibilities relationships interactions

Generating and characterizing diverse approaches Comparing their concrete strengths and weaknesses

Page 6: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 6

What Are Design Patterns?

Design Patterns are “mini-architectures” Unitary, easily named (Command, Session

Façade…) Applicable to small, recurring problem spaces Templates of responsibilities, relationships and

interactions Complex problems often map to a combination of

patterns

Page 7: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 7

What's a Framework?

A framework instantiates an architecture and set of patterns

Concrete software package with classes, APIs, etc. (e.g. Flex, Cairngorm, JSF)

Further nails down scope and nature of solution Specific responsibilities, relationships and

interactions Implies set of possibilities and constraints Gives you pros and cons; do you need the pros?

Page 8: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 8

What We'd Like in a Flex Application

Isolate presentation, state, actions, communication Cope with unpredictability of UI design, remote server Parallelize design, client coding, server coding Respond instantly to user actions, provide good

feedback Handle cross-cutting concerns:

testability logging security error handling

Page 9: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 9

Flex Client ReviewTube: a mashup between YouTube.com (a popular video publishing site) and a custom Comment Server

adds caption display synchronized with cue points in YouTube videos

YouTube provides metadata and media

custom Ruby on Rails server provides add-on caption data (and mirrors relevant metadata)

Sample Flex Application

YouTubeServer

CommentServer

MediaService

CommentService

Views

Cont

rolle

rMetadata Media Captions

XML / HTTP

Page 10: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 10

Views

Services

Flex Client Architecture: Models, Views, Controllers, Services

MediaService

CommentService

VideoPlayer

Cont

rolle

r

interface interface

VideoBrowser

Login,Search…

Models

Collection

VideoInfo

Comment

Comment

populates

referencesnotifies

com

mun

icate

s

inte

ract

s

Session

inte

rfac

e

Page 11: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 11

The Model: Representing State

Represents all client state as objects, collections, properties

All state changes dispatch events (and Bindable vars implicitly do this)

Does not refer to any non-Model application component

Model

notifies

Collection

VideoInfo

Comment

Comment

Session

Page 12: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 12

The View: Presentation and Interaction

Presents application state (the Model) to the user Encapsulates all user interface design Responds to user interaction by invoking Controller operations Responds to Model change notifications by updating itself typically MXML plus some fraction of AS

Views

VideoBrowser

VideoPlayback

Login,Search…

Model

references

notifiesController

inte

ract

s

Page 13: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 13

The Controller: Exposing Actions, Invoking Services

Encapsulates all user-initiated actions in the application

Modifies Model as needed Invokes Services as needed Manages indirect view-to-

view relationships acts as Façade for:

miscellaneous application logic

progress and error reporting confirmation, validation security and authentication

Views

ServicesCont

rolle

r

Modelinte

rfac

e

Page 14: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 14

The Service Layer: Remote Operations and Logic

Encapsulates all communication with the outside world Populates Model objects with remote data Logical place for stubs early in development or as test harness Caching and other performance enhancements can be easily added

Services

VideoService

CommentService

interface interface

Model

populates

com

mun

icate

s

Page 15: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 15

Code Break!

Let's look at a simple Model/View/Controller interaction

Page 16: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 16

Interactions: Model, View, Controller, Service

VideoBrowser

gest

ure

User initiates gesture, searching for videos by tag

Page 17: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 17

Interactions: Model, View, Controller, Service

Co

ntro

ller

VideoBrowser

getVideosByTag()

View asks Controller to get the videos

Page 18: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 18

Interactions: Model, View, Controller, Service

CommentService

Cont

rolle

r

interface

VideoBrowser

getVideosByTag()

loadVideos(model)

Controller uses Service to load videos into a model

Page 19: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 19

Interactions: Model, View, Controller, Service

CommentService

Cont

rolle

r

interface

VideoBrowser

modelgetVideosByTag()

loadVideos(model)

Eager Model Creation: Controller returns model (still empty) to View

Page 20: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 20

Model

Interactions: Model, View, Controller, Service

CommentService

Cont

rolle

r

interface

VideoBrowser

dataProvidermodel

getVideosByTag()

loadVideos(model)Collection

View binds Model as its dataProvider, listening for change events

Page 21: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 21

Model

Interactions: Model, View, Controller, Service

CommentService

Cont

rolle

r

interface

VideoBrowser

…server results

dataProvider

Collection

VideoInfo

VideoInfoco

mm

unica

tes

Service processes server response, populates model

Page 22: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 22

Model

Interactions: Model, View, Controller, Service

CommentService

Cont

rolle

r

interface

VideoBrowser

dataProvider

binding changesCollection

VideoInfo

VideoInfo

upda

tes

Model emits event notifications, triggering View updates

Page 23: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 23

MVCS In Summary

Model: semantic data only View: interaction and presentation only Controller: actions, mediation, cross-cutting

concerns Services: communication only

Page 24: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 24

Approaches to Model Implementation

Value Object Classes: vehicle for uniform data representation in client All properties should be Bindable All collections should implement ICollectionView or IList

Data only, no behavior allowed! Ease of consumption by Views should usually drive

design Make data binding convenient!!! Not identical to server representation Minimize rearrangement of server data structures

Page 25: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 25

The Asynchronous Tango: Services and Operations

Many operations require similar handling in the Controller: they don't complete immediately when complete, the results are used to populate Model objects need status, progress, error reporting

Command pattern: Controller works with Operation objects which expose a uniform interface for completion, status, error handling, etc.

Factory pattern: Service can act as factory for Operations returned to caller; the Service properties (e.g. host URL, protocol, etc.) apply to all its Operations

Composite pattern: Operations can be composed into a higher-level CompoundOperation that executes its children in sequence

Page 26: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 26

Interactions: Controller, Service, Operation

CommentService

Cont

rolle

r

interface

loadVideos(model)

Collection

Page 27: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 27

Interactions: Controller, Service, Operation

CommentService

Cont

rolle

r

interfaceIO

pera

tion Video

QueryOperation

new VideoQueryOperation(model)

loadVideos(model)

Collectionvideos

Page 28: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 28

Interactions: Controller, Service, Operation

CommentService

Cont

rolle

r

interface

command

loadVideos(model) IOpe

rati

on VideoQuery

OperationCollectionvideos

Page 29: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 29

Interactions: Controller, Service, Operation

CommentService

Cont

rolle

r

interface

loadVideos(model)

Collectionvideos

execute()

IOpe

rati

on VideoQuery

Operation

Page 30: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 30

Interactions: Controller, Service, Operation

CommentService

Cont

rolle

r

interface

status events

loadVideos(model)

videos

XML/HTTP request and response

server results

StatusViewsactivity status and progress

VideoInfo

IOpe

rati

on VideoQuery

OperationCollection

execute()

Page 31: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 31

Interactions: Controller, Service, Operation

CommentService

Cont

rolle

r

interface

completion event

loadVideos(model)

videos

VideoInfo

IOpe

rati

on VideoQuery

OperationCollection

execute()

Page 32: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 32

Sample Controller Code

from Controller.as:

public function getAllVideos():ICollectionView { var data:ArrayCollection = new ArrayCollection(); performOperation(commentService.loadAllVideos(data)); return dataProvider;}

public function logout():void { performOperation(commentService.logout());}

public function performOperation(op:Operation):void { showStatusText(op.displayName); op.addEventListener(Event.COMPLETE, operationComplete); op.addEventListener(ErrorEvent.ERROR, operationFailed);}

Page 33: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 33

Sample Service Code

CommentService.as:public function loadAllVideos (dataProvider:ArrayCollection):Operation{ return VideoQueryOperation.allVideos(this, dataProvider);}

VideoQueryOperation.as:public var videos:ArrayCollection;

public static function allVideos // static factory method (s:CommentService, dp:ArrayCollection): void{ var c:VideoQueryOperation = new VideoQueryOperation (service.urlPrefix + "/all"); c.videos = dataProvider; return c;}

Page 34: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 34

Approaches to View Implementation: The Fundamentals

If you don't code to enable reuse, it won't happen! Set child properties to communicate "inward". Avoid

using functions; you can't use data bindings with them Dispatch events or set Bindable properties to

communicate "outward" (code example: VideoTimeStrip) Components shouldn't know what type container they

go in Containers shouldn't know what's inside their children

Temptation: MXML id-based properties are always public! Refactor ruthlessly

Page 35: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 35

Approaches to View Implementation

Use inheritance to separate view logic (ActionScript)from layout and styling (MXML) Examples: LoginPopup, RegistrationPopup Superclass in ActionScript; specifies common

properties and function definitions Superclass public var x:Component

may be overridden in subclass by <Component id="x"/>.

Page 36: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 36

Approaches to View Implementation

Childless MXML componentsA "childless" MXML superclass can customize

superclass properties and be used as a component itself in some other MXML file (with optional children).

For example, SmallCanvas.mxml might contain simply:<mx:Canvas mx:width="32" height="32"/>

Some other component can then use:<SmallCanvas> <SomeChildComponent/></SmallCanvas>

Page 37: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 37

Cool Binding Patterns

If you want a property change to have some kind of side effect in your component, bind to a setter function that does the work.

example: YouTubeVideoDisplay requests URL when video property changes

You can bind a function of a Bindable:<mx:Label label="{DateTimeUtils.formatOffset(time)}"/>

You can bind an expression with multiple Bindable inputs; it will be reapplied if any input changes.

<mx:Button enabled="{canRegister(password.text,repeatPassword.text)}"/>

Factor out expressions like that, by binding to a local Bindable: [Bindable]

var registrationOK:Boolean;<mx:Binding source="canRegister(password.text,repeatPassword.text)}" destination="registrationOK"/>

Page 38: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 38

Miscellaneous Tips

Never assume properties will be set in a well-defined order Bindings can fire in an unpredictable, indeterminate

sequence Example: CommentCaption's treatment of comment,

videoOffset

All event handling functions should be privateIsolate style/skin knowledge: always prefer styleName

to explicit styles

Page 39: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 39

The Cairngorm Framework

It's well conceived and executed Many people like it It handles many of the issues discussed here Some differences: usage of Command, Responder,

Locator patterns Semi-aligned with concepts in J2EE Core Patterns Strong reliance on event broadcasting for user

actions

Page 40: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 40

Avoiding The Dark Side

Preconceived vs. emergent approaches Force-fitting problems to patterns:

“If I have a hammer, this must be a nail” Using patterns needlessly:

“That looks like a nail, I must need a hammer” Satisfy key needs, not possible needs Abstraction costs time: use it at obvious “hinge

points”

Page 41: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 41

Do you need something specialized and simple….

Page 42: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 42

Or something more general, but tricky to maintain?

Page 43: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 43

The Land of Many Right Answers

There's always more than one way to do something Business and politics do influence technical approaches, like it

or not Patterns and practices in the end are a tool to meet one's real-

world needs

Page 44: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 44

Resources

Sample code, updates to presentation can be found at:

http://joeberkovitz.com/max2006/

Page 45: MAX 2006  Flex Best Practices: Applying Design Patterns and Architecture

2006 Adobe Systems Incorporated. All Rights Reserved. 45