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.

Continue reading ‘ActionScript 3.0 Protection Proxy Design Pattern 2: The FCNY Meeting’

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

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.
Continue reading ‘ActionScript 3.0 Protection Proxy Design Pattern 1: Shielding the Real Subject’

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.)

Continue reading ‘ActionScript 3.0 Lazy Initialization and the Factory Method Design Pattern’

Recursion vs. Iteration: Elegance or Speed?

recur_vs_iterRepeated operations are handled either by recursion or loops (iteration). One of the fundamental structures of programming is loops, and we programmers tend to think, If I need to repeat an operation, I use a loop. Loops are built-in structures of most languages, and ActionScript 3.0 has multiple options when it comes to loops. ActionScript 3.0 has the standard for (and variations), while, and do statements as well as looping methods for arrays and vectors. So if we need to repeat a set of operations, we have several iterative statements that will get the job done for us.

Why Bother With Recursion?

In most (but certainly not all) situations, iteration is faster than recursion, and so why should we even consider recursion? Recursion is nothing more than a method that can call itself that uses more memory than iteration and fills up the stack quickly. You’ll get a stack overflow with recursion both with big numbers and with infinite loops. Loops can handle big numbers better, and while they eventually blow a gasket with an infinite loop, they take longer to do so because iterations are not stored on the stack.

Despite what some programmers would see as the end of the conversation comparing iteration with recursion, I was able to find two good reasons to consider recursion over iteration.

  1. The code can be clearer and simpler
  2. Recursion offers more elegant solutions

With the caveat that the following is not a call to abandon loops, let’s take a look at the reasons you should consider recursion the next time you come across a task that requires repeating operations.

Clear and Simple

Sometimes we come to a problem where we want to lay out all of the options to better see what’s going on. With loops, especially with complex ones that involve nesting, we can quickly find ourselves spinning our wheels. On the other hand with recursion, we can lay out the steps in a series of statements that clearly show the options we have to consider.

For example in the previous post on this blog examining the construction and use of skip lists, the search algorithm uses recursion. In the stripped down version of the search method, we can clearly see the repeated steps taken in the search routine:

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public function searchList(searchKey:uint,layNum:int):int
		{
			this.searchKey=searchKey;
 
			if (initial)
			{
				layNum=4;
				searchNode=headNode;
				initial=false;
			}
 
			if (searchNode.contents==searchKey)
			{
				trace("success");
				return searchNode.contents;
			}
\
			if (layNum&lt;0)
			{
				trace("Number not found");
				return -1;
			}
 
			if (searchNode["skip"+layNum].contents< =searchKey)
			{
				searchNode=searchNode["skip"+layNum];
			}
 
			else
			{
				layNum--;
			}
			return searchList(this.searchKey,layNum);
		}

The steps are clear to see how the search works its way through the skip list to find whether a given value were included:

  1. If it’s the first time through, begin at the top level in the head node.
  2. If the search key matches the node contents end the search and return the found contents.
  3. If the layer is below 0; end the search and inform the user that the value was not found.
  4. If the next node is greater than or equal to the search key, the search node becomes the next node
  5. If the next node is less than the search key, move down a layer
  6. Run function again if nothing is returned

Continue reading ‘Recursion vs. Iteration: Elegance or Speed?’