Archive for the 'Flex' Category

Page 3 of 7

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

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.

Continue reading ‘Guest Post: Pieter Grobler- Understanding Design Patterns through Science Fiction’

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

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

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

ActionScript 3.0 Interpreter Design Pattern: A PostScript Tutor

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.
Continue reading ‘ActionScript 3.0 Interpreter Design Pattern: A PostScript Tutor’

No Time for OOP and Design Patterns

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?

Continue reading ‘No Time for OOP and Design Patterns’

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

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.

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