Archive

Archive for the ‘Design Patterns’ Category

Measuring the Goodness of ActionScript 3.0 Design Patterns

September 9, 2010 6 comments

Why Design Patterns are Hard

Why Design Patterns are Hard

How Come they Get Calculus and We Get Sticks and Arrows?
I’m still playing with Skip Lists: A Probabilistic Alternative to Balanced Trees by William Pugh. I have yet to work up an ActionScript 3.0 solution for both inserting new data into a skip list and deleting data from one—even though there’s lots of code that shows how to do it. It’s more fun to look at Pugh’s article with the pseudo-code that he provides to show how to insert/delete data in skip lists. Were I working to figure out a design pattern, I’d be looking at a bunch of association arrows, dashed line instantiation trails and diamond-tailed aggregation spears—just like poor old wound man.

Some of the key parts of Pugh’s article, along with lots of articles you see in professional programming journals have all of these cool formulas. If you’ve seen Flash Math Creativity: 2nd Ed by Keith Peters and some other folks, you’ve seen lots of formulas like the one’s in Pugh’s article although Flash Math Creativity tends to be more trigonometry and geometry than calculus—in any case they’re über cool.

So how do we calculate the efficiency of Design Patterns? The algorithm crowd gets all kinds of cool formulas from every nook and cranny of math—even statistics in some cases. However, in going through The Gang of Four’s Design Patterns, there’s not a single formula that has that kind of proof.

Here’s What I’m Talking About…

In discussing how to work through the cost of running a skip list versus a balanced tree, Pugh offers the following formula:

C(0) = 0
C(k) = (1–p) (cost in situation b) + p (cost in situation c)

which he follows up with:

C(k) = (1–p) (1 + C(k)) + p (1 + C(k–1))
C(k) = 1/p + C(k–1)
C(k) = k/p

Eventualy he comes up with the total expected cost to climb out of a list of n elements as:

L(n)/p + 1/(1-p) which is O(log n)

In all of this, C(k) is the the expected cost —length— of a search path that climbs up k levels in an infinite list. So now Pugh can take his formula to the Balanced Tree makers, and say,

See, my formula proves that Skip Lists work as well as Balanced Trees and they take less effort.

So with formulas you can demonstrate mathematically and using math logic that a certain course of action is a reasonable one. So where do we start looking for formulas that can:

  • Help determine which pattern to use
  • Prove that a design pattern is a better choice over a non-design pattern

Why not start with OOP principles and see if they can help?
Read more…

Share

ActionScript 3.0 Protection Proxy Design Pattern 2: The FCNY Meeting

FCNY Meeting

FCNY Meeting

On June 30, 2010 I met with the Flash Coders New York (FCNY). I walked over to the meeting site from Grand Central Station—it’s a straight shot up Park Ave., dogleg at Broadway and Bob’s your uncle! It’s right there near 4th on Mercer in a joint called Think Coffee. (East Village area near NYU.) I was lugging my Mac PowerBook and it and the case weighted 11 pounds. (After the two mile hike, my computer felt considerably heavier. If you plan to go, you’ll find that the subway— #6 to Brooklyn Bridge—from Grand Central is easier.)

Making Changes to the Original Protection Proxy

FCNY meets in the basement room at Think Coffee that reminded me of a (smoke free) anarchist’s safe house. (I was expecting to see Sacco and Vanzetti there.) They helped me hook up my PowerBook to a projector, and off we went. Having found myself in a perfect storm of doing the author edits of a Flash Catalyst book and starting on another new book, I was pressed for time; so I took the protection proxy from this blog and changed the proxy participant to include an algorithm that would filter out different “levels” of access. The level of sophistication of the algorithm and the added classes for different levels of access were quite simple. However, the point is to focus on the design pattern and not my acumen at writing algorithms. (If you don’t like the algorithms, you can always re-write them and send them in.) You can download the package by clicking the download button—the .zip file includes the PPT/KeyNote pages as well.
kilroy

What was most exciting for me was the fact that the Protection Proxy was so easy to change. Here was a program with several different classes, and I had to add new functionality in a hurry that did several different things that would not crash my program. Essentially, I was adding three new concrete RealSubject classes that would work with the current program and make changes in the Proxy (SubProxy) to filter through three different “level of access” options. I knew that if I followed the interface rules, no matter what algorithm I used, it’d work. Figure 1 shows the class diagram of the revised Protection Proxy (from the FCNY presentation.)

<em><strong>Figure 1: </strong>Stratified Protection Proxy</em>

Figure 1: Stratified Protection Proxy


The three RealSubject participants (International, National, Local) are pretty much the same except that each loads a different text file. However, as long as each maintains the interface, no matter how different the algorithms are, everything happily hums along.

Read more…

Share
Categories: Proxy Pattern

Meet in NYC on June 30, 2010

fcnyI’ll be at the Flash Coders New York (FCNY) weekly meeting at Think Coffee, 248 Mercer St. (NYC) on Wednesday, June 30 (Time: 7-9pm) to talk about ActionScript 3.0 Design Patterns. The plan is to look at some of the fundamental principles of design patterns and implementations with ActionScript 3.0. The Protection Proxy used in combination with PHP and multiple levels of access is the planned application that will be discussed plus any other ActionScript 3.0 Design Pattern of interest. Bill

Share

ActionScript 3.0 Protection Proxy Design Pattern 1: Shielding the Real Subject

Proxy and Real Subject

Proxy and Real Subject

The images that people use on dating sites may not exactly represent who they are. So instead of putting in a real picture, they may use a proxy that is better looking, younger (or older), and generally more likely to attract a date. The Proxy Design Pattern deals with object access. In our book, we employed an unusual proxy, the Symmetric Proxy Pattern that uses a remote proxy. In fact, it uses mirrored proxies to access two different objects simultaneously. Our example showed how to use it with Flash Media Server, and so probably not a lot of developers use it as a model for understanding a Proxy pattern. However, on this blog we provided a virtual proxy that should be a clear and simple example of a Proxy design pattern. So, we covered two of the three Proxy designs. The sole remaining type is the Protection Proxy, and that’s what we’re going to look at now. (You can run it and download the files using the buttons below:)

playkilroy

The Easiest Proxy

Of all of the Proxy designs, the Protection Proxy is very simple both in terms of implementation and concept. The Client makes a request to the Proxy, and the Proxy decides whether to give the Client access to the Subject. Where more than a single Subject is available, the Proxy decides on the level of access. For example, we started off with an example of a dating site. Some users have no access to the dating site until they sign up as a customer. Basically, the Proxy denies them all access to the subject. Once they sign up, they may be given access only to a specific gender. For example, the girls may only be given access to boys if that’s who they’re interested in meeting. The Proxy controls that access. Also, they may be given access only to change their own profile; again controlled by the Proxy. Of course the site administrator needs total access so that he can make sure that no one is posting materials that they shouldn’t be. (When I posted that I was an Astronaut, Rock Star who owns a Silicon Valley software company, the administrator changed it—and without my permission!.)

This design requires only three participants to implement : Subject (interface), Proxy and RealSubject with the Client making a request through the Subject interface to the Proxy. Figure 1 shows the Proxy class diagram shows and the different relationships:

<em><strong>Figure 1:</strong> Proxy class diagram</strong>

Figure 1: Proxy class diagram

The sequence is unique in that the request, while for the RealSubject, goes through the Proxy as shown in the object diagram in Figure 2:

<em><strong>Figure 2: </strong> Proxy object diagram</em>

Figure 2: Proxy object diagram

As you can see, the Proxy design is pretty straightforward, and given the three modes (remote, virtual, and protection), it’s versatile. However, in looking at it, it doesn’t seem to do too much in terms of loosening up code and reusability. According to the GoF,

The Proxy pattern introduces a level of indirection when accessing an object. The additional indirection has many uses, depending on the kind of proxy: p. 210

So the key to understanding the Proxy pattern is indirection. We need to consider indirection a bit more, which we begin on the next section.
Read more…

Share
Categories: Proxy Pattern

ActionScript 3.0 Lazy Initialization and the Factory Method Design Pattern

Lazy Initialization

Lazy Initialization

The other day I was re-reading Chandima’s description of key OOP concepts used in the Factory Method design pattern. It is beautifully encapsulated in a little over a half a page (page 84). The Factory Method allows you to separate the creation of objects from their use. It says a bit more, but it is a nice piece in both describing a design pattern principle and explaining what the Factory Method does. This led to re-reading the Factory Method chapter in Design Patterns: Elements of Reusable Object-Oriented Software—the Gang of Four’s book. Normally, I just go over the main points, but I came across a little passage that read:

Just be careful not to call factory methods in the Creator’s constructor—the factory method in the ConcreteCreator won’t be available yet. (page 112)

The comment was directed at some issues in C++ which may or may not have any bearing on ActionScript 3.0, but just in case it did, I continued reading. The point being made was you can avoid these problems by accessing products only through accessor operations that create products on demand. So what are accessor operations? Generally these are public methods that you can call to initiate creation of a product.

Time Out! Before we get too far ahead of ourselves, you can download all of the .as files for the Factory Method example by clicking the following button:
kilroy

The example is a simple one that creates three different shapes—ellipse, rectangle and triangle. Figure 1 shows how the Client arranged them to display a house in front a a pond with a cloud overhead:

<em><strong>Figure 1:</strong>Triangle, Ellipse and Rectangle Products</em>

Figure 1:Triangle, Ellipse and Rectangle Products

The program uses concrete creators to fetch shapes. The Client makes requests that size, color, and position the shapes.

Don’t Enslave Your Constructor Functions

This issue of the constructor functions reminded me of a post by Miško Hevery, the guy at Google who helps set Google’s programming standards. One of the key flaws in a program is where the constructor does real work. Besides violating the single responsibility rule, Miško goes on to explain the tell-tale signs that one has used his constructor function with outrageous disregard for both agile programming and loose coupling. As a result of reading Hevery’s work, a year or so ago, I began to seriously gear back on using a class’ constructor function; primarily by not including one in most of my classes. (My Client class is a glaring exception to the rule.) I’d usually have just the properties and operations (methods, functions) that I needed. The properties would initialize themselves—sort of. They’d be given an ID and then typed and that was all. The child classes could then use them in operations. Whenever I needed something, the Client would type a request to the interface (including abstract classes) and then make a request through concrete method in an operation. With the Factory Method, I make requests to the ConcreteCreator through the abstract Creator class.

In returning to GoF, they point out,

Instead of creating the concrete product in the constructor, the constructor merely initializes it to 0. (Page 112)

In this discussion, they note that Factory methods in C++ are always virtual functions. WTF?! (What’s That Function?!) Simply stated, any function that can be overridden in the child classes is a virtual one. Well, we can do that in ActionScript 3.0. In fact, that’s what we do in creating Abstract classes. (Why we can override and yet not have real Abstract classes is still a mystery to me.)

Read more…

Share

Design Patterns with Missing Pieces

Why are Participants Missing? Note: Gentle reader, This article was written for our new PHP Design Pattern blog, but the points apply as well to ActionScript 3.0. As a result, I decided to include it here. The links in this post have been changed to go to the relevant ActionScript 3.0 posts, but otherwise, the article is the same. After writing design patterns in PHP for a while, I’ve come to appreciate the strongly typed structure of ActionScript 3.0. Programming to the interface in PHP is tricky, but possible. However, when you have strong typing as ActionScript 3.0 does, you really appreciate it more once you’ve worked with a dynamic language without strong data typing.

The Case of the Missing Participants

Recently I was working on a Decorator pattern and struggling through PHP’s way of doing things. So naturally I thought why not take a look at how others have solved these same problems. The Gang of Four refer to the different classes and interfaces that make up a design pattern, as participants, and when I look at a design pattern, the first thing I do is to see how the developer handles the different participants. What I found was surprising—they left out chunks of a design pattern in their examples. Alternatively, they just did some kind of workaround that effectively made it work (run), but it was no longer a design pattern or had the advantages of a design pattern.

The Strategy with the Missing Context

The Strategy pattern decouples the algorithms from the Client by using a Context class. All of the requests for the algorithms (found in concrete Strategy classes) go through the Context to the Strategy interface and on the the implemented strategies in the form of concrete classes. However, in many of the PHP examples, they leave out the Context class and Strategy interface and go directly from an Object to concrete Strategies. In several examples, the code authors chose to ignore the interfaces and even the abstract classes and have fairly direct connections between concrete strategies and some kind of object. Figure 1 shows the kinds of UMLs that accompany these kinds of PHP design pattern implementations—if indeed they are implementations.

Figure 1: Minimalist UML

You can see clearly that the UML in Figure 1 has little in common with the class diagram we used that was an exact replica of the Strategy pattern that the Gang of Four uses.

The authors of this kind of “explanation” of the Strategy pattern seem to think that the separation of the algorithms from the object is a matter of nothing more than taking the algorithms out of some object and using them independently of the main object. However, while that is an improvement on cramming everything into a single object (class), it is not a design pattern. Yes, it does add flexibility because more than one class can use the same concrete strategies. So, it’s a step away from single-class programming and even procedural programming. However, it is not a design pattern and it does not have the design pattern’s flexibility. The Context class uncouples the request from the strategy and without it, that concrete strategies are tightly linked to the “object”—whatever that may be.
Read more…

Share
Categories: Design Patterns

How to Pick the Right Design Pattern: Fortune Favors the Prepared Mind

Deciding on a Design Pattern

Deciding on a Design Pattern

Which Design Pattern Should I Use?
One of the most difficult questions to answer is also the most often asked: How do you know what design pattern to use? My standard response to that query is,
Ask, “What varies?”

Of course, it seems that everything varies just when you need a nice clear answer to that question. The Gang of Four provides a list of design patterns and what varies in each pattern—such as states of an object, an algorithm, responsibilities of an object without subclassing and so on. However, determining the nature of the variation can be as difficult as deciding the design pattern to use as looking at class diagrams. (Download the AIR version of the Variation Table—also known as The Magic Table.)

Go To The Original Source

Chapter 1 in the Gang of Four’s book is the gateway to design pattern knowledge. I must have re-read it 50 times. Further, every time I re-read it, I get something new. You can download Chapter 1 of Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides—just click the download button to bring up the PDF file and then save it:
kilroy

Find the section, How to Select a Design Pattern and read it. Even if you don’t get it all the first time through, you’ll have a better idea of design pattern selection. Now you’re all set to continue with the rest of this post. Read on!
Read more…

Share
Categories: Design Patterns

The ActionScript 3.0 Design Pattern Thrill Ride: Part II—Catalyst

Thrill I’ve been working on a project with Adobe Catalyst, and if I didn’t do something for a Design Pattern tour now, it would be put off until I don’t know when. So I put together a non-design pattern application incorporating video and code snippets from the Aid Game. I simply have not had time (given the work I’m doing with Catalyst) to put together a more generic design pattern “thrill ride” that I planned; so while I’m working with Catalyst, I thought I’d might as well do something with design patterns and came up with this more mild tour instead of my planned thrill ride. Figure 1 shows what it looks like:

<em><strong>Figure 1: </strong>Tour through State Design Pattern</em>

Figure 1: Tour through State Design Pattern

As you can see it’s pretty simple—sort of a PowerPoint chat. (Nowhere near as flexible as the one created with the Memento pattern.) So, if you’re interested in a mild tour, click the Play button and hop on:
play

By the way, the Catalyst project has made me far more aware of Flash Builder/Flex code. It uses Flex in its engine. If you’re interested in Catalyst, you can download the Beta at Adobe Labs. I tried importing programs (SWF files) made with design patterns, and it works great. About the only thing I didn’t do with this tour is to put the videos on Flash Media Server—sorry. I was in a hurry and wasn’t sure how to link up FMS to Catalyst. I could have written the code in Flash/Flex and created an SWF file to import into Catalyst, and that works fine, but I’m pretty pressed for time on this project.

As always, your comments and valuable feedback is encouraged. I’ll be back working on this blog as soon as I’m finished with the Catalyst project. Besides, Chandima has been writing knock-out posts to keep you interested!

Share

Separated Presentation: The Classic Model-View-Controller Pattern

This is not an introduction to the MVC pattern, but a look into its implementation in Smalltalk-80 to understand the original intent and function of the Model, View, and Controller triad. Starting with the “classic” MVC helped me understand the evolution of the presentation patterns that came after it. We will look at how a simple MVC app works in Smalltalk-80 and examine how it can be implemented in ActionScript. I am not a Smalltalk programmer and my first task was to find some good resources.

Trygve Reenskaug is credited with the first MVC formulation in Smalltalk in the late 70′s. However, the MVC metaphor was burned into Smalltalk and matured after Reenskaug left Xerox Parc. I found two useful resources on MVC in Smalltalk-80. The first is  A cookbook for using the model-view controller user interface paradigm in Smalltalk-80 by Glenn Krasner and Stephen Pope. The second resource is Applications Programming in Smalltalk-80: How to use Model-View-Controller (MVC) by Steve Burbeck.

Although comprehensive, Krasner and Pope’s article is very readable from an ActionScript perspective. I could just about follow the Smalltalk code listings, identify the early OOP features and appreciate the ancestors of contemporary UI components.  What stood out was how little things have changed in the last 20 to 30 years in OOP and GUI programming. I think the more appropriate observation is how advanced Smalltalk was for its time. Krasner and Pope’s essay is the primary resource for this post.

Model-View-Controller Implementation in Smalltalk-80

The MVC pattern facilitates the separation of concerns when developing interactive graphical applications. The logic and state of the application, how users interact with the application, and how application state is presented to the user are handled by separate elements of the MVC triad. Smalltalk-80 uses the MVC metaphor to provide built-in support for interactive application development. The idea was to provide a set of built-in user interface widgets such as buttons, menus and lists that can be plugged into a GUI application. To use these built-in UI widgets effectively, the application had to be built in accordance with the MVC metaphor. Let’s take a look at the conceptual diagram of a Smalltalk-80 MVC app.

Model-View-Controller (from Krasner & Pope)

Conceptual diagram of MVC in Smalltalk-80 (from Krasner & Pope)

All objects in Smalltalk communicate with each other via messages. Think of messages as a way to invoke methods in an object.

At first glance, the MVC conceptual diagram seemed a little strange. The multitude of arrows indicated more acquaintances than I’m used to seeing in an MVC diagram. Model-View and Controller-Model dependencies ran both ways. The second interesting aspect was that user input goes directly to the Controller. This is a significant change as we generally expect users to interact with UI widgets in the View. In Smalltalk-80, it looks like the raw keyboard and mouse input is fed directly to the Controller. Let’s take a quick look at how the MVC metaphor is supported in Smalltalk-80. Read more…

Share

New Aid Game: The Machine Moves!

February 2, 2010 37 comments

Helper Class is Helped

Helper Class is Helped

I wanted to move on from the original Aid Game, at least as far as the movement was concerned; so I fully fixed it up. With the new set of rules from the previous post of repairing the movement, I realized that if I didn’t generate fully operating movement states, we’d end up overly focusing on the wrong things. So, I set up a class (TimeMachine) to encapsulate the Timer object, and then the Mover class became the child of the TimeMachine using the different TimeMachine Timer properties. Because I instantiated a Timer object in each of the properties in the TimeMachine, I do not believe it is properly an Abstract class. However, like an Abstract class, it is not invoked directly, but rather through inheritance.

Playing the Game by the Rules: First Break the Rules

The nice thing about a State design pattern is that once the rules are established, you can build your algorithms and the different states invoke them according to the rules you’ve established. You can have a number of different algorithms within the State framework, and they should all work in accordance with the rules—no matter what the rules are or what algorithms you use to invoke them.

To see if the revised game follows the movement rules, try and break the rules. The main rule that you can attempt to break is the No reverse without stopping rule. So if you’re going right and you press the Left button, your helicopter should first stop and then you’d have to press the Left button a second time. Or you can reverse direction by pressing the Stop button and then press the opposite direction. Click the Play button to give it a whirl:

play

So go ahead and try to break the rules! If you can; then the design fails. If not, it succeeds. Once you’re finishing playing, download the latest code and see how the rules were applied.

kilroy
Read more…

Share
Categories: State