Archive for the 'ActionScript' Category

Let’s Get Rid of Conditionals!

No Conditionals Please
At the 2007 OOPSLA Conference in Montreal, a professor from New York City was explaining how he taught his introductory computer science classes. Students would be given a problem and they’d go through a number of steps until the solution failed. He found that most of the failures occurred as students became entangled in ever more elaborate conditional statements.

To resolve this problem, he told them they could not use conditional statements, and the general results were both better solutions and better coding. My first reaction in one of the breakout sessions was “No way!” Back in the day, one of my favorite pastimes was working out sort algorithms, and I find it hard to imagine working out even a simple bubble sort without using conditional statements. Other examples quickly came to mind, and I dug in to defend the use of conditional statements from if to switch (and everything in between).

Then he mentioned three magic words: State Design Pattern. This got my undivided attention because of the work I’d done with them and more generally, State Machines. Each class in a State Design Pattern is made up of a set of functions that launch when a certain state in invoked. No if’s in sight. Triggers launch different states, and the state classes provide the context for the particular state. In other words, the triggers just call the state class desired.

Aside from the State Design Pattern, can a decent program be written without a single conditional statement when more than one condition needs to be considered? I think it can be, and I’m beginning to think that much better programs can be developed if conditionals are kept out. To illustrate a simple decision-making process with no conditional statements, the following program has a decision-making process based on user input.

package 
{
	import flash.display.Sprite;
	import fl.controls.Button;
	import flash.events.MouseEvent;
 
	public class Unconditional extends Sprite
	{
		private var men:String;
		private var women:String;
		private var Button1:Button;
		private var Button2:Button;
 
		public function Unconditional ()
		{
			men="Men";
			women="Women";
 
			Button1=new Button();
			Button1.label=men;
			Button1.x=200, Button1.y=150;
			addChild (Button1);
			Button1.addEventListener (MouseEvent.CLICK,doMen);
 
			Button2=new Button();
			Button2.label=women;
			Button2.x=200, Button2.y=200;
			addChild (Button2);
			Button2.addEventListener (MouseEvent.CLICK,doWomen);
		}
		private function doMen (e:MouseEvent)
		{
			trace ("Whatever is appropriate for men");
		}
		private function doWomen (e:MouseEvent)
		{
			trace ("Whatever is appropriate for women");
		}
	}
}

That was a simple program, and it could have been handled with a single method using a conditional statement.

But It Would Have Been Easier….
In thinking about this, you may be thinking of a long list of cases used in a switch statement or even a simple if...else sequence make a program possible. (I mentioned sort algorithms, and I’m sure you can think of others where you just had to have conditionals.) Often, (in fact usually) it’s easier to use conditional statements than to work out a lot of code that does the same thing. However, no one who took up design patterns was looking for an easier way to create code. In my experience, there’s nothing easy about design pattens except when it comes to the all important task of updating and changing a program. So, because it’s easier probably is not the best argument to preserve conditional statements–at least for readers of this blog.

Why Conditionals?
Rather than ask why not conditionals, I think we need to ask why conditionals? Why indeed? If a programmer wants something to happen given an event, ranging from user input to data from a Web service, the event should trigger the actions directly rather than first filter through a conditional statement. It cuts out a step (the conditional scratching its head) and goes right to the solution. So why even use conditionals? Yes, we’re all used to them, but most of us were used to either sequential or procedural programming before tackling OOP or design patterns. If we can get along without conditionals, and keep a direct link between the state to call an action and the action, it would seem to be a better programming structure. Then, when we want to make changes, the events are not tied into a conditional statement, and we don’t have to untangle the conditional webs we weave.

Comments Please
I’d really like to get some feedback on this idea. If you’re thinking, That’s the stupidest thing I’ve ever head, I’ll save you the trouble–that was my initial thought, and it didn’t really help the discussion. Rather, I’m hoping to find some ideas about this — with or without the State Design Pattern. Mainly, I’m interested in this in the context of design patterns in general; specifically how conditionals or lack of them relate to the different kinds of connections between classes. Do they really get in the way of delegation, composition, aggregation and inheritance? Are they simply a shortcut and add little to good structure? Or not?

The Flyweight Design Pattern: Where Shared Objects Solve Storage Problems

Note: After three Flyweight Saga entries, I think I have all of the parts explained and working like they should. To double-check, the following was presented at the 2007 OOPSLA conference in Montreal. The great comments that the readers of this blog provided were most helpful, and further comments by those in the OOPSLA Killer Examples session all added to what I hope works to clarify using the Flyweight Design Pattern with ActionScript 3.0. Also, everything in this article is based on Design Patterns Elements of Reusable Object-Oriented Software by the Gamma, et al.

Air traffic controllers look at virtual simulations of hundreds of aircraft. The images on a screen give the ATCs the information they need for separating the many planes under their control. The hub airports such as Chicago O’Hare and Dallas-Ft. Worth have to juggle hundreds of simultaneous flights arriving at and departing from their respective airports. To maintain accuracy, images that display position, heading, altitude, level flight, ascent and descent must be updated frequently, accurately and quickly. In looking over the set of design patterns set forth by Gamma, et al, the Flyweight pattern offers the following:

  • An application uses a large number of objects
  • Storage costs are high because of the sheer quantity of objects
  • Most object state can be made extrinsic
  • Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed
  • The application doesn’t depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects

That pretty well fills the bill for what is required. We need a large number of objects (airplane images), the sheer quantity has high storage costs, the extrinsic state such as heading, horizontal position and vertical position can be made extrinsic, once extrinsic state is removed, a few objects can be used to represent groups of objects, and the application is not dependent of object identity. This is not to say that one cannot be distinguished from the other, but rather the object identity is relative to its extrinsic characteristics.Figure 1 shows the basic class diagram.


Figure 1: Class Diagram

The key elements of the class include the following:

  • The Flyweight class, (an abstract class or interface) with the operation with parameters for the extrinsic states.
  • A Flyweight Factory that aggregates the Flyweight class. (The ball at the end of the aggregation arrow indicates that multiple aggregations may exist.)
  • A Concrete Flyweight contains the extrinsic states and the intrinsic states. This is a shared object
  • (Optionally) An unshared concrete Flyweight containing the extrinsic state but cannot be shared.
  • A Client participant. The Client class in this design pattern has a responsibility and has acquaintance relations with both the concrete flyweights and the factory classes.

Continue reading ‘The Flyweight Design Pattern: Where Shared Objects Solve Storage Problems’

The ActionScript 3.0 Flyweight Saga: Part III Aggregation Aggravation, Stuff on the Stage and the Intrinsic State

Aggregation Aggravation

In the first installment of this Flyweight Saga, I noted that the relationship between a Flyweight and Flyweight Factory class is one of aggregation. The initial example shows that the Retrieve method in the Factory class returns an instance of IFlyweight, meeting the requirement of the proper connection between the two classes. In looking at one example in Java, (even with modest Java skills), the program clearly did not have such a relationship between the Factory and Flyweight. In fact, it claimed, that an object’s extrinsic state can be shared by classes. Now, maybe that was unfortunate wording because the big feature of the Flyweight design pattern is that the Flyweight can be a shared object, but only the intrinsic state can be shared. (Maybe the author meant that extrinsic states can be shared between classes in a Flyweight design pattern, and that’s probably right but is not a key feature of the pattern.)

Anyway, after looking at several different descriptions of aggregation, including the one provided by the GoF, it’s clear that the concept is one with fuzzy borders and can slip into either general composition or acquaintance. It implies that the Flyweight Factory aggregates the Flyweight—no Flyweight, no Factory. As a result, the life of the aggregator (Flyweight Factory) depends on the life of the aggregatee (Flyweight). Like acquaintance, aggregation is implemented with references or pointers rather than defining variables of once class in another. (Apparently C++ is an exception and does set up aggregation by defining variables from the aggregatee class.)

By and large the issue has not been especially significant so far because all of the output was using trace statements, and so output was largely confined to built-in features that only work when the code is run in test mode. It’s great for debugging up to a point, but developing with trace statements that do not take into account how certain graphic elements, especially those that are accessed by extending the Sprite classes, can generate unusable structures for applications that employ graphics and other elements that require the import and extension of other classes. In this next Flyweight example, we leave the realm of trace and use the graphics property (from the Sprite class) to draw solid balls using fill methods. The ball class extends Sprite and implements the interface. That’s all fine and good, but the aggregation becomes problematic in even the simplest example. In taking the general structure from the examples examined up to this point (Parts I and II of the Flyweight Saga), we can begin to see the trouble.
Continue reading ‘The ActionScript 3.0 Flyweight Saga: Part III Aggregation Aggravation, Stuff on the Stage and the Intrinsic State’

Flexibility Pays Off with Template Method

This is a testimonial of sorts for the capacity to easily change an application created with design patterns. Recently Adobe put up a version of a player that streams H.264 formats–these are files like Apple’s .mov and MP4, among others. After fumbling around for a while creating the files–one video .mov using iMovie and a M4a audio using Garage Band, I went to test them on a progressive download app I had handy that was set up to play audio using the Sound class and video with NetConnection(null) and NetStream. The only problem was that the streaming audio (m4a) file required a NetStream instance and would not work with the Sound class.

Because the classes for handling audio were set up around the Sound class, I thought this would be a major chore, but all I had to do was to make changes in one class. After the changes were made, it worked fine. The best part is that the structure of the Template Method did not interfere with any of the other elements in the application. So while the application may be fairly complex for the simple task of playing video and sound, when things change, as they always do, making the changes in the application were simple.

The application can be found at: http://www.sandlight.com/player9/. Keep in mind that no FLV files are used but that a genuine MOV file being played in Flash using progressive download and the sound is from a M4a file, the same file format as the ones used for iTunes–all sitting fat and happy and working. You’ll need to go to Adobe Labs and download the Flash 9 player (Beta) to see this at work.

Transitioning to the Desktop with Adobe AIR

Video of Lee Brimelow’s session from AIR Camp Denver. Lee does a fantastic job of placing Adobe Air in the crowded field of Flash, Flex, Microsoft’s Silverlight and desktop apps. He demos several apps showing the capabilities of AIR apps including custom chrome and most importantly, the impressive speed of AIR apps running on the desktop, including several that use the Papervision3D library. He also shows how to create AIR apps using the excellent AIR Panel developed by the folks at gskinner.com (Note: Adobe now has an update for creating AIR apps from Flash CS3).

AIR opens a whole new discussion about best practices on developing desktop apps integrating ActionScript, HTML, Javascript and PDF and how to integrate design patterns that work seamlessly across multiple development frameworks.