Archive

Archive for the ‘Flex’ Category

Take a Design Pattern to Work Part I: Identifying the Problem

January 1, 2009 7 comments

New Year’s Resolution

Happy New Year! Now’s the time to resolve to be better in many ways, and one compartment of improvement for me is in programming. In this time of multitasking, I find that I can do a lot better if I focus on one thing at a time, and so compartmentalization really helps—sort of like encapsulation. Further, I find it helpful to have a plan on how to go about whatever change I want to make; so this year my plan is step-by-step to improve my programming habits. However, the first step is to identify the problem and deal with the realities in the problem.

Lions Led by Asses

During World War II in North Africa, one German commander described the British army as lions led by asses. Now I’m not one to claim that developers should take over management and lead us all to a new day and brighter world. However, on occasion I’ve run into situations where someone makes seriously stupid demands that can waste time and possibly destroy a project. Let me share the kind of real-world situation I’m talking about.

During one project, I created an example of bringing in content from external text files using ActionScript 3.0. The example was to show how to create dynamic text in a simple text file so that customers could change text files and maintain the content of their own Web site. For the content I provided an example of travel to very poor countries by a clueless vacationer. One of the people responsible for reviewing the program examples threw a tizzy fit and claimed I was mocking poor countries and demanded that I re-do the entire program. (Actually I was mocking the lack of awareness of poverty, but the reviewer didn’t get that either.) As anyone reading this blog realizes, all I had to do was to change the content of the example text file, and that would solve the problem of what was viewed as political incorrectness.

A long time ago I learned to pick my battles carefully. So rather than going into a detailed explanation of what I was attempting to do and taking a stand against what I saw as monumental ignorance, I simply changed the content of the text file (which was the whole point of the example in the first place). That took all of 10 minutes. The reviewer had every right to tell me to change the content of the example, but she was way out of her depth in telling me to re-write the whole example. That would have been a waste of time and messed up a useful example. She was totally unaware of what the example was all about—the content was immaterial. It was all about flexibility in using ActionScript 3.0 and allowing customers to make changes on their own. Much later in the project, I got a follow-up email from a manager checking to make sure the example was changed. I assured her it was and sent her the revised text files as proof. There was no big fight, angst, and, most importantly, wasted time and effort. We all have only so much psychic energy. It’s the kind of energy we use for working out algorithms, design patterns and other cognitive chores. You’ve only got so much before your brain says, “Enough! I’m pooped!” Don’t waste it on unnecessary fights or gnashing your teeth over bad decisions or unfortunate management choices.

Read more…

Share

Guest Post: Pieter Grobler- Understanding Design Patterns through Science Fiction

December 24, 2008 2 comments

Gentle Readers: Chandima and I decided to try something new. Pieter Grobler wrote a science fiction story to bring out the key elements in the Chain of Responsibility design pattern. We hope that the story will be helpful in grasping some of the main concepts in the pattern. Most importantly, though, we need your feedback. Tell us what you think. Should we run more such stories or not? Chandima and I will continue doing what we do, but we are interested in other creative approaches such as Pieter’s. So use the comment box to give us your feedback.

Conquering Ratas (CoR)

The Hissians are a peaceful people. For generations, they have had to stand up against a great threat – not from the outside worlds, but a threat that are inherently part of themselves. In the face of danger, a Hissian has the ability to pass on the Message – a telepathic sort of communication, linked to only one other inhabitant. To the day, it remains an inexplicable passage of consciousness between all living creatures of the planet. Yet, calling on this power exerts great physical effort, and has proven to be fatal in the past.

Recently, there has been an ensuing series of threats from the neighbouring planet of Ratas, the home of ill-willed, brutal barbarians. For this reason, a soldier was sent out to Ratas to investigate the nature of the threats. He is brutally killed and sent back home, badly mutilated. Accompanying the gruelling package, is a warning message implying that Hissa would be harshly punished for their offensive curiosity.

So, Hissa prepares for the attack by way of setting up a defensive effort, which is planned and rehearsed to the letter, based on sensitive information supplied by Irgir, a Ratasian student under the great Hissian Philosopher, Riughadas. The plan rests on the idea to have Yarayara, the old lady of Pagh, pick berries in the area where the Ratasian forces plan to land. Her magical and seductive powers will then subliminally persuade them to try the Paghiby Berries – a rare cultivar with poison so strong, that it instantly boils the consumer’s blood, causing a biological malfunction, which creates such pressure in an organism, that its structure inevitably tears itself up, obliterating all surroundings in the violent process.

But this has been doomed to failure since the beginning, for its application was too specific, and the foreign soldiers were in no mood for tasting berries. Instead, they prompted Yarayara to prove the planet’s good intent by eating them herself. As she knew her fate, she ran her veinous hand down the scarf that her daughter – her only family – had given her. Brutal murder followed as homes in the peaceful village of Pagh were raided, their inhabitants pinned to the walls, left there as dripping trophees of Ratasian rage.

Then, on a beautiful morning, soaked in a reddish glow from the Star, it happened. Young Eileva, a selfish and spoilt girl was waddling away from her mother in teenage rage, when she saw the black masses of Ratasian soldiers approaching. She hesitated, only to be swept into a primal, instinctive urge to notify her predestined successor – her mother. And, as soon as the Message had reached her mother, Eileva bounced on the ground, her rotund little body progressively accelerating down the meadow.

Read more…

Share

ActionScript 3.0, Design Patterns and Polymorphism: What’s the Point?

December 19, 2008 25 comments

*Note to our gentle readers: This is one of those blog entries that probably raises more issues than it resolves. Further, it requests reader input. Consider yourself forewarned.

Why Polymorphism?

As just about everybody reading this blog knows, polymorphism is a foundational concept in object oriented programming (OOP). We devote several pages to polymorphism in our introductory chapter showing what it can do and what it looks like using several examples. (In fact I think we did a pretty decent job) However, I still don’t have the same kind of intuitive sense for polymorphism as I do for encapsulation, inheritance and some of the other concepts that make up OOP and more importantly, design patterns.

I went to my bookcase and found lots of discussion of polymorphism, and on the Web I found lots more. What’s missing (for me at least) is a visceral connection between polymorphism and design patterns. We can all talk about overloading methods, using interfaces to achieve polymorphism and provide all sorts of examples. But that’s not the same thing as smoothly working in polymorphism as a thought pattern when programming. I wondered if anyone else had the same minor intellectual itch that I do, and lo and behold in the Wikipedia entry on type polymorphism I found the following note:

All or part of this article may be confusing or unclear.

Such a notice is another way of saying it doesn’t make a lick of sense. This is not to say that the explanation is inaccurate. Technically, it’s very accurate as far as I could see. It’s just not very clear.

Read more…

Share

ActionScript 3.0 Interpreter Design Pattern: A PostScript Tutor

December 14, 2008 3 comments

ActionScript 3.0 Interpreter Design Pattern

Back in the day I used to do a lot of FORTH programming. For about 10 years I’d attend a weekly meeting of FORTH programming engineers at General Dynamics in San Diego and marvel at what they could do with this postfix language. (Postfix is often called reverse Polish notation after the Polish mathematician Jan Łukasiewicz who developed the mathematical notation placing the operator after the operands.) The following shows an example of this notation:

30 2 * 4 +
Result: 64

Later, when Adobe came out with PostScript and Apple came out with their first laser printer, I was able to program in PostScript using a text editor and shooting it directly to the printer. Out would come these fabulous fonts, drawings and whatever else I had programmed in. Because PostScript used a similar postfix notation as FORTH, I was allowed to do a FORTH newsletter in PostScript. Only a few were produced since it was no easy task to develop a newsletter in code using Notepad! (Click here to see the final PostScript calculator that this application generates. It works with PostScript data entry — use add, sub, mul, and div for +, -, *, and / respectively.)

Interpret This!

The Interpreter design pattern as described by Gamma, et al can be used to express instances of a recurring problem as sentences. Interpreting the sentences then solves the problem. Right off the bat I was thinking, ¿como está usted? translates to how’s it going? but that’s not exactly what GoF had in mind. Any spoken language is a bit too big for this kind of interpreter. Instead, the pattern describes how to define a grammar for simple languages. Gamma and his associates use the example of regular expressions, so loved by Perl programmers.

So when I went looking at some Interpreter examples, besides regular expressions, I found converters from Roman numerals to regular numbers, a Boolean language, a musical note interpreter from do, rey, me, fa, so, la, ti to Hertz (Hz) values, calculations using postfix notations and some other fairly modest examples. Because of my experiences with postfix languages, I decided to do one that set up as a PostScript data entry that would resolve to an outcome (solution) to the results of a postfix statement. I decided on PostScript whose math operators are word-like and not symbols. (e.g., Instead of using / for division, it uses div.) This would be a little more than the usual minimalist example since the user can use it to practice and learn PostScript math entries.

Interpreter Design Pattern Formal Features

Figure 1 provides an overview of the Interpreter pattern. Note that the Client is part of the pattern (instead of implied or not at all). Also note that the Client holds references to both the Context class and AbstractExpression interface.

Figure 1: Interpreter Class Diagram

Of all of the design patterns I’ve seen, this one has the most loose ends. Any statement put into a string and then interpreted generally requires some kind of parsing. GoF note the need for parsing and point out it can be from a table driven source, a recursive descent (or some other hand-crafted parser) or in the Client. The Context class is used as a global entry point for the Interpreter. It’s probably heresy to do so, but I decided to put the parser in the Context. The Client sends the request to the Context and indirectly to the AbstractExpression. The Context class still acts as a global entry point, but it also parses the data (statement in PostScript notation), and the Terminal Expression classes still do the actual interpretation. I don’t see it as adding tighter coupling. (If the parser were placed in the Client, I suppose it would be a purer version of the design pattern. If you think so, I’d like to see your implementation, and I’d be glad to put it on this blog.) Also, like most of the examples that I saw, this one does not include a NonterminalExpression. That is because I did not need alternation, repetition or sequence expressions.

The good news is that this implementation of the design pattern is wonderfully flexible and easy to update. If I wanted to change the language example from PostScript to something like Scheme, the pattern would be able to handle it with ease. Eventually, I’d like to re-do it with the parser in the Client and add several PostScript drawing commands by adding more terminal expression classes. I’d also like to add a NonterminalExpression for handling certain repetitions and sequences.
Read more…

Share

No Time for OOP and Design Patterns

December 7, 2008 45 comments

Some years ago, a Canadian band named The Guess Who (not to be confused with the better known Who) had a song titled, No Time. Recently, three unrelated events occurred that gave me pause and reminded me of the song and doing coding in the real world. (By the way, this is a post that we’d really like to get your comments on and experiences in working with ActionScript 3.0 in the real world.)

The Deadline and Short Life

The first event occurred while talking with an agency that is a heavy user of Flash and ActionScript. During our chat, one of the developers said, “You know, we usually don’t do it right,” referring how they programmed ActionScript in Flash. The comment was right out of the blue, and at the time I briefly wondered what he was talking about. The manager added, “We’ve got deadlines, and they’re going to want new projects almost immediately.” It dawned on me that they were saying when push comes to shove, they had to get paid and nobody wanted to hear excuses about a late project because of some perfectionist quibbling about OOP or design patterns. I asked them, “You want programmers who know how to do it right, though?” and almost in unison, they said, “Of course.”

This particular agency produces both beautiful and functional materials. On top of that, they have a complex relationship with developers, graphic designers, HCI designers, managers, other projects competing for company resources, a budget and of course, clients. So getting a project out the door is not a matter of a developer/designer tucking away in a cozy cubicle and developing a product in a vacuum. As though reading my mind, they added, “We almost never have the same project requirements more than once.” Hence, why spend time on a project when it’s a one-off, and it will be off the shelf after a few months of singing the virtues of a product or service? Why indeed?

Read more…

Share

ActionScript 3.0 Visitor Design Pattern: A Tale of Traverser and the Double-Dispatch Kid

December 6, 2008 10 comments

The Visitor design pattern allows you to add operations to classes without changing the classes. That pretty well summarizes what the Visitor can do for you. Imagine you’ve got a great big game program and you want to tweak the functionality of certain objects in the game by adding operations (methods and functions). Rather than opening a bag of marbles to spill out in every direction when you add functionality to a class, all you need to do is to use the Visitor to add that functionality without interfering with the rest of the class. If you’ve read Chandima’s chapter and posts on the Composite pattern, you’re two jumps ahead. Typically, the Visitor is used with a Composite pattern. Likewise, Chandima’s post on the Iterator will aid in understanding the traverse process used in the Visitor. Of course you can work perfectly well with the Visitor without background in these other patterns, but you might want to peek at them for further reference and understanding as you review the Visitor.

The Visitor Design Pattern’s Formal Features

First, take a look at the Visitor’s class diagram. You will note that the implied Client holds references to two different classes within the pattern. The factory patterns (Abstract Factory, Factory, Flyweight) all have similar multiple references from the Client, and so too does the Command, Interpreter and Iterator patterns. So don’t let the multiple references from the Client throw you. Figure 1 shows the Visitor class diagram:

Figure 1:Visitor design pattern diagram

The Client reference to the Visitor interface (IVisitor in the example program) sets up implementations for concrete visitors. The concrete visitors visit the different concrete elements. At the same time, the client goes through the ObjectStructure and the ObjectStructure has multiple object references to the Element interface. The black ball at the end of the ObjectStructure reference arrow means that it has multiple references. Figure 2 isolates that relationship from the Visitor diagram.

Figure 2: Multiple object references

Getting the ObjectStructure and its references to the Element class is an important part of working successfully with the Visitor pattern.

Double-Dispatch

One of the key processes behind the Visitor’s ability to add operations to existing classes is the double-dispatch technique. Like the name implies, double-dispatch involves two receivers. A single-dispatch involves the name of the request and the type of receiver. In double-dispatch the executed operation depends on the kind of request and two receivers. In the Visitor example program, you will see that the accept method is a double dispatch operation. Within a concrete element, it is written as:

public function accept(visitor:IVisitor):void
{
    visitor.visitConcreteElementA(this);
}

The this statement refers to the Concrete Element class it is contained within. In this context you can see the visitor and element receivers that make it a double-dispatch operation. The actual operation that is executed depends on the type of Visitor and Element. Using this technique allows you to consolidate the operation in the Visitor.

Read more…

Share

ActionScript 3.0 Strategy Design Pattern: Under No Conditionals

November 9, 2008 9 comments

Strategies Eliminate Conditional Statements

If this entry evokes a sense déjà vu, you’d be half right. It is not another jibe to condemn conditional statements, but instead it is a discovery of another pattern where you can eliminate them. The consequences listed by Gamma, et al for the Strategy pattern includes,

Strategies eliminate conditional statements.

While I am quite familiar with the fact that the State design pattern eschews conditional statements, I was unaware that the Strategy pattern has the same feature. Rather, like everyone else I focused on the dictum, encapsulate the concept that varies when dealing with the Strategy pattern. Here I do not plan to re-hash what we covered in Chapter 11 of our book, but instead I want to look at a simple Strategy design pattern where no conditional statements are used. Also, I want to walk through a thought process when working on a simple application and show how flexible it is because of the Strategy design pattern.

It All Began with a simple MP3 Player

Creating an MP3 player in Flash is something I’ve done often and never gave it a second thought using the NetConnection and NetStream classes. However, recently I was working on one using the Sound and SoundChannel classes. Turning it on and off was trivial, but I learned that unlike the NetStream class, the SoundChannel class has no pause method. (NetStream has both toggle and non-toggle versions of pause methods.) The SoundChannel has a position property that returns the position of the MP3 file currently playing. By passing the position value to a variable and passing it to a play() method as a parameter, the play would resume where it left off. So building a player using either NetStream or SoundChannel is not rocket science.

However, suppose you decide to have a structure that could use either the NetStream or SoundChannel class. To that you might also add whether you wanted the MP3 to play on the NetStream as a progressive download or as streaming audio through Flash Media Server 3. All you have to change is the content of the algorithms to accommodate any of the three versions you envision. Of course you don’t want to dismantle all of the other work if you decide to change the program. You just need to change the algorithms.

The Abstract Architecture of a Strategy MP3 Player

When you get right down to it, you only need four algorithms:

  • Start Play
  • Stop Play
  • Pause Play
  • Unpause Play

Depending on what you have set up in the Client class for a UI and the types of classes you’re using to play the MP3 files, the details of the algorithms will vary, and you may even have a class to organize the Sound/SoundChannel or NetConnection/NetStream methods. For now, though, all I want is architecture to handle starting and stopping play and pause. This will also help reveal the structure of the Strategy design pattern. Figure 1 shows the Strategy pattern that is used in this example:
stratuncondfit

Figure 1: MP3 Player Strategy Design Pattern

The IPlayer interface is the Strategy portion of the pattern. All of the algorithms go into implementations of IPlayer, and so all we need will be four concrete strategies—one for each of the actions on the MP3 player. For this example, I’ll just use trace() statements to act as stand-ins for actual algorithms.

Context Class

The left part of the class diagram in Figure 1 is the Context participant in the pattern. As shown in the diagram, the Context class holds a reference to the Strategy (IPlayer) participant. That reference to the IPlayer can be seen in the following listing:

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
 
package
{
	public class Context
	{
		protected var player:IPlayer;
 
		public function doControl():void
		{
			player.control();
		}
	}
}

Read more…

Share

ActionScript 3.0 Prototype Design Pattern: A Minimalist Example

October 28, 2008 10 comments

The Recursive Clone

In describing the Prototype design pattern, the Gang of Four indicate that in the collaborations, the client asks a prototype to clone itself. (Go clone yourself!) As innocuous as that sounds, it turns out to be more than a little work, and the pattern, as GoF indicates, is tricky and easy to get wrong. With ActionScript 3.0, my response is, “…you have no idea!

In a couple of earlier articles relating to the Prototype design pattern in this blog (ActionScript 3.0 Clone and ActionScript 3.0 Recursive Excursion) we looked at some of the issues relating to key elements of the Prototype design pattern, and if you’re thinking of using the Prototype pattern, you might want to take a look at them and some of the comments that readers have made. I’d prefer not to re-hash them here so that we can focus on the design pattern and not its components or underlying processes that we’ve already discussed. So to get started, let’s take a look at the Prototype class diagram in Figure 1:

Figure 1: Prototype Design Pattern

Because the pattern includes a Client class, you can see right away where the client connects to the other participants in the pattern and something about the nature of the relationship. The key here is that the client holds an object reference to the Prototype class. So the client is going to have some kind of Prototype reference.

Read more…

Share

An ActionScript 3.0 Recursion Excursion

October 23, 2008 16 comments

Recursion is one of those things I’ve been thinking about lately because of the recursive classes in the Prototype pattern. However, recursion isn’t something that I think about much, but at the OOPSLA conference in Nashville that is just now wrapping up, it came up in as a favored method over loops. A professor from Cornell University was making a presentation at one of the sessions I attended, and he noted that they introduce students to recursion before introducing loops , getting enthusiastic approval from some in the audience. Because I’ve been beating my head against the Prototype pattern, this was more than a little interesting. What’s so special about recursions?

Another Loop?

In some respects, recursion is just another looping structure, but programmers tend to think about them differently, and I thought I’d see what I could find from some of the big brains at OOPSLA. I talked with Dr. Axel Schreiner about recursion and got all I could ever imagine anyone would want to about them. However, like many, he considered recursion to be a loop structure and didn’t seem to be particularly excited whether loops or recursive structures were employed. For Axel, recursion and looping were a matter of looking at repeated actions in different ways.

Defined, a recursion is a method (or function) that can call itself. That doesn’t sound like a loop, but it does have a repeating element in that a recursive function repeats a process by the simple fact of calling itself. The most common examples of recursion is a factorial, but Fibonacci sequences and Towers of Hanoi are other common examples used to illustrate recursion. Since Fibonacci sequences are one of those just plain cool math structures, I thought I’d start with a Fibonacci sequence.

A Fibonacci Example

A Fibonacci sequence is one where each number in a sequence is made up of the sum of the previous two in the sequence. The sequence begins with 0 and 1:

0 1 1 2 3 5 8 13 21

Rather than using a loop to generate the sequence, the recursive function in the following example takes a parameter (r) and returns the next value in the sequence after r. The following class calls the recursive function via a trace() statement. (I was using Flex, but Flash works fine for the same function.)

?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
/*Fibonacci  generated in a recursive function*/
package
{
	import flash.display.Sprite;
 
	public class FibRecursion extends Sprite
	{
		public function FibRecursion()
		{
			trace(fibo(8));
		}
 
		private function fibo(r:uint):uint
		{
			if(r==0)
			{
				return 0;
			}
			else if (r==1)
			{
				return 1;
			}
			else
			{
				return fibo(r-1) + fibo(r-2);
			}
		}
	}
}

The recursion occurs in the third return statement. That is, part of the fibo() function calls itself. As you will see, the output is,

21

The question is, what’s going on inside the cursive function?

Read more…

Share

Is MVC Obsolete? Flex, ActionScript 3.0 and the MVC Design Pattern

October 12, 2008 15 comments

Another View of the MVC Design Patterns

A while back Brian Lesser, another O’Reilly author and top notch Flash Media Server developer, mentioned that he did not especially care for the Model View Controller (MVC) design pattern. While he cited some references, I never paid much attention to it at the time, especially since Chandima kept writing these brilliant pieces on Pure MVC. Further, I had promised myself that I wouldn’t touch MVC until I had worked my way through all of the design patterns using ActionScript 3.0 and felt comfortable with Flex. So I really am no expert of MVC and have relied on Chandima for that particular compound design.

After weeks of pounding my head on the Prototype pattern, I was thinking of taking a break and sending a torpedo into the Singleton to let off some steam. However, before sticking my neck out (yet again) I thought I’d ask Brian why he didn’t particularly care for the MVC, resulting in a very thoughtful article. (See http://broadcast.oreilly.com/2008/10/mvc-as-anti-pattern.html) Brian asked for Chandima’s and my reaction. Not having spent that much time on the MVC, my reaction was based on the logic of the article which to me made perfect sense. However, this is a case of “What do I know?” The annual OOPSLA conference is coming up this next week and I will be bringing up Brian’s points to big brains that attend OOPSLA–and I hope some more Flex/ActionScript/Flash developers will be there this year! So maybe after next week I’ll have some comments from seriously bright programmers in addition to our seriously bright programmer, Chandima.

So take a look at http://broadcast.oreilly.com/2008/10/mvc-as-anti-pattern.html and we’d like to get any copies of your comments, thoughts, and wisdom that have you about Brian’s article to post here as well.

Share