Archive

Archive for the ‘Principles’ Category

Beginner's First Design Pattern: The Template Method

I'm a Design Pattern Virgin too!

It's my first time too!

The Template Method: A Design Pattern with a Principle

In learning OOP and Design Patterns, what you’re learning is a set of principles with associated programming patterns. The Template Method is a valuable starting place because it is used to illustrate the OOP/DP principle called The Hollywood Principle. Be sure to go over the more detailed post on the Hollywood Principle, but for here, you just need to become familiar with the idea that higher level components (like parent classes and interfaces) should call lower level components (like concrete classes), but lower level components, should not call higher level components. The principle is called Hollywood, because the casting director tells the budding actor,

Don’t call us, we’ll call you.

The parent class tells the child class the same thing.

Class Diagram

In order to understand a class diagram, you need to understand class relations. If you understand how to work with an UML, you’re ahead of the game; however, if not, we’re prepared a 4-part series to help you understand the UML and the whole concept of relations between pattern participants. Figure 1 shows the class diagram for the Template Method:

<em><strong>Figure 1: </strong>Template Method

Figure 1: Template Method Class Diagram

After you’ve studied the class diagram for a bit, you can see that it’s made up of one abstract class (all italicized bold lettering indicates an abstract class or interface), and one subclass. One of the operations in the abstract class is concrete (Template Method) and the others are abstract (primitive operations). The abstract methods are italicized.

The template method is made up of the steps in an algorithm, some of which are abstract and some that can be concrete. The template method orders the steps in the algorithm, but the concrete subclass provides concrete implementations of the abstract methods using override. The following two buttons provide a preview of Play and all of the files are available for download:
playkilroy

Abstract Classes and Primitives

One of the more poorly defined concepts in computer programming is that of primitives. Usually when we think of primitives, we think of basic data types like numbers, strings and Booleans. However, the Gang of Four parenthetically note that primitive operations are nothing more than abstract methods. For example, the following is an abstract operation (or method):

?View Code ACTIONSCRIPT
1
2
3
4
5
protected function DoUI():Sprite
{
    throw new IllegalOperationError("Must override");
    return null;
}

Because ActionScript 3.0 has no abstract classes or methods, you have insure that the abstract methods will not be directly instantiated, and one way to do that is to add the illegal operation line. Further to have the proper signature, the method must include some kind of return statement, and a null value does the trick. In the concrete implementation, each primitive operation is overridden and provided concrete operations.

Within the abstract class, you can have both concrete and abstract methods. One of the advantages of an abstract class (compared with an interface) is that abstract classes can have some concrete methods. For example the following template method uses two primitive operations and a concrete one. It’s just is to order the steps of the algorithm, which in this case has three:

?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
...abstract class..
 
public function templateMethod()
{
	DoLogo();
	DoUI();
	DoInfo();
}
 
protected function DoUI():Sprite
{
	throw new IllegalOperationError("Must override");
	return null;
}
 
protected function DoInfo():TextField
{
	throw new IllegalOperationError("Must override");
	return null;
}
 
protected function DoLogo():Sprite
{
	var logo:Sprite=new Sprite();
	return logo;
}
 
...abstract class

So let’s stop a second and consider why and how we’d use a Template Method design based on the following:

  1. An abstract class
  2. A method that orders the steps in an algorithm
  3. At least one abstract method that is overridden by a concrete class that implements the abstract class.

The abstract class affords the programmer flexibility when similar algorithms are used again and again but with slightly different implementations. For example, you may find yourself using a “page algorithm.” The page algorithm loads your logo, creates a UI and then creates content. The logo loading part is going to be the same as you use your logo over and over again. However, the UI and content can vary in several different ways. For that, you need flexibility.

Page Arranger

To get started on the algorithm for a page arranger, we’ll start with the abstract class which is named IServices. One convention you will find in OOP is using an “I” prefacing all Interfaces. I like to do the same thing with abstract classes because other than the concrete properties and methods, you should think of them as a type of interface. (If you’re just getting started in OOP and Design Patterns, you might want to check out Beginners Start to see where the files go in Flash and Flash Builder.)

?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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package
{
	import flash.display.Sprite;
	import flash.errors.IllegalOperationError;
	import flash.net.URLRequest;
	import flash.display.Loader;
 
	//Abstract class. Do not instantiate directly
	//Extend the class for concrete child classes
 
	public class IServices extends Sprite;
	{
 
		private var logoPix:URLRequest=new URLRequest("logo.swf");
		protected var uiPix:URLRequest;
		protected var infoPix:URLRequest;
		private var logoLoader:Loader=new Loader();
		protected var uiLoader:Loader=new Loader();
		protected var infoLoader:Loader=new Loader();
		private var page:Sprite=new Sprite();
		private var logoSprite:Sprite=new Sprite();
		protected var uiSprite:Sprite=new Sprite();
		protected var infoSprite:Sprite=new Sprite();
 
		public function templateMethod():Sprite
		{
			page.addChild(DoLogo());
			page.addChild(DoUI());
			page.addChild(DoInfo());
			return page;
		}
 
		protected function DoUI():Sprite
		{
			throw new IllegalOperationError("Must override");
			return null;
		}
 
		protected function DoInfo():Sprite
		{
			throw new IllegalOperationError("Must override");
			return null;
		}
 
		protected function DoLogo():Sprite
		{
			logoLoader=new Loader();
			logoLoader.x=0;
			logoLoader.y=0;
			logoLoader.load(logoPix);
			logoSprite.addChild(logoLoader);
			return logoSprite;
		}
	}
}

In the abstract class IServices, you can see two abstract methods (primitive operations), and two other methods—DoLogo and templateMethod. The DoLogo is going to be the same assuming that the company keeps the same logo; so you might as well set it up and let the child classes reuse it when they extend the abstract class. However, the UI and information may change, and so both of the methods for what they may include are left up to the concrete implementation.

Next, enter the concrete implementation of the abstract class. In the following you will see that both of the abstract methods are not implemented.

?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
package
{
	import flash.display.Sprite;
	import flash.net.URLRequest;
	import flash.display.Loader;
 
	public class ConcreteService extends IServices
	{
		override protected function DoUI():Sprite
		{
			uiPix=new URLRequest("UI.swf");
			uiLoader=new Loader();
			uiLoader.x=0;
			uiLoader.y=110;
			uiLoader.load(uiPix);
			uiSprite.addChild(uiLoader);
			return uiSprite;
		}
 
		override protected function DoInfo():Sprite
		{
			infoPix=new URLRequest("info.swf");
			infoLoader=new Loader();
			infoLoader.x=150;
			infoLoader.y=110;
			infoLoader.load(infoPix);
			infoSprite.addChild(infoLoader);
			return infoSprite;
		}
	}
}

Keeping in mind that you never implement an abstract class, but you want to program to the abstract class (think interface), you will need a client class to request the use of the concrete implementation. However, by declaring the requesting instantiation through the abstract class, you can keep the binding loose. So the variable tm is typed to IServices but instantiates ConcreteService.

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
package
{
	import flash.display.Sprite;
	public class Client extends Sprite
	{
		private var tm:IServices=new ConcreteService();
		public function Client()
		{
			addChild(tm.templateMethod());
		}
	}
}

As you can see, there’s not much work for the Client. All it has to do is to use addChild to place the returned Sprite object to the display area. The templateMethod() operation is wholly inherited from the IServices class, but at the same time the ConcreteService class allows flexibility of what goes into the DoInfo and DoUI methods.

Play around with this example. The best way is to create some .swf files that you can use instead of the ones provided for download on this post. You’ll begin to see how flexible this design pattern is and how easy it is to use.

Share

ActionScript OOP and Design Patterns: Why Bother?

January 30, 2011 21 comments

evolution
At a workshop not long ago I found myself saying,

I’ve got nothing against 4th Graders.

It was in relation to the MVC, which is the precursor to the Gang of Four’s catalog of patterns, but it’s appropriate in this discussion as well. Originally, I was asked what I had against MVC, and I said, Nothing, and I’ve got nothing against 4th graders either. The reference was to getting stuck in the MVC in a continuous loop—just like getting stuck in the 4th grade. The MVC is brilliant because it helped free programmers from monolithic conceptualizations in programming. However, it’s a starting point; not an ending point. The Pure MVC advocates certainly agree with that idea, and that’s fine, but pure or (impure?) MVC, it’s still an MVC. The GoF make the point that different patterns can be developed around what varies in an application, and the MVC is a way to deal with UIs and has much in common with the Observer pattern; which leaves some 20 other patterns that focus on different variations. (Later developments of the MVC have elevated it to an architecture.)

In my own case, I got stuck on the State pattern for about a year and decided that it was time to move on after realizing that other patterns would serve me better when something other than state varies. Redoing my Web site now, I wish I had used design patterns in more than the video player I made with a State pattern.

Why OOP? What’s Wrong with Sequential Programming?

First off, let’s get straight what we mean by sequential programming. In one context, it means Not Parallel Programming or Not Concurrent Programming. Just ask anyone at Intel. They think that everyone should learn concurrent programming based on the fact that their processors are all multi-core, and single core processors have gone the way of the Dodo bird. They’ve got a point. In looking at my collection of computers my old Win XT may be single core, but I’m not even sure that’s it’s not a dual core. My Macs and Win 7 (64-bit) systems are all dual or quad core. (See Joe Duffy’s book, Concurrent Programming on Windows for about 1,000 pages of info on this kind of programming.) Just to be straight about the point, that’s not the kind of sequential programming I’m talking about.

In this post, I’m referring to non-structured programming where you just write one line after another. When I used to write assembly language programs (especially using the assembler I wrote myself) everything was non-structured. Likewise, a lot of the Basic programming I wrote was sequential along with Fortran and non-Pascal stuff. If I had to put a date on it, I’d guess such programming is about 60-70 years old. It’s not old school; it’s just old.

What’s wrong with sequential programming? Is it slower? Does it not execute correctly? Are there algorithms I cannot write with it?

No to all of the above.

It’s main shortcomings center around the spaghetti factor. After not too many lines of code, it’s easy to get tangled up. If your programs are short, you’ve got little to worry about with good ole’ sequential programming. Otherwise, sequential programming is difficult (near impossible) to maintain, change and keep straight.

However, you’d be amazed by the number of programming books that still present coding in nothing but sequential structure—which is non-structured. (In the past I’ve been guilty of the same thing; so I’ll be throwing no stones.) Some authors who have attempted to do otherwise have been snarled at…What about the beginners? What about the non-developers?! Grrrr! So it’s not just complacent code-writers who create programs in nothing but sequential structures; some authors do the same.

To be fair, a lot of the code in computer books is presented in snippets—little bits of sequential code to explain the syntax or to provide a working example. That’s fine and not what I’m talking about. In good books all of the bigger examples are in OOP or at least procedural programming. What I’m talking about are books where everything in the book is presented as sequential programming. One I have in mind showed a three-tiered if statement that was part of a bigger sequential monstrosity. How that mess helps beginners is beyond me. (By the way, the particular book I have in mind was published in 2009 by one of the most reputable computer book publishers in one of the most respected series.)

Oddly I found that by working with design patterns I end up doing simple sequential snippets—none of the messy spaghetti stuff. Read on to see why.

Read more…

Share

ActionScript 3.0 Saturated Abstract Factory 3: What is a Single Responsibility?

November 29, 2010 6 comments

Moving from Inheritance to Composition

Moving from Inheritance to Composition

Parameters of Responsibility

While waiting around for someone to offer up a dynamic client for the Abstract Factory, I started thinking about the whole concept of single responsibility. This is nothing new, and we have a post on the topic, but it’s one of those things that keeps nagging at me, and I thought it’d be a good topic of discussion. What keeps buzzing around my mind is the concept of single. In team sports, different positions are assigned different responsibilities. One of the most unique positions is that of the goalkeeper (or goalie) who is the only member of the team who can use his hands. So I thought that it’d be a good idea to begin with the goalkeeper.

The Duties of a Goalkeeper

Classes should have only a single responsibility

Classes should have only a single responsibility

In the game of soccer (football or fútbol to the rest of the world) what are the responsibilities of the goalkeeper? Any fútbol fan can list several, but in the context of a soccer team, the goalkeeper has certain focal responsibilities and not others. For example, the goalkeeper is not expected to leave his post and attempt to score a goal. That’s the responsibility of the striker (forward or even midfielder), but not the goalkeeper.
Read more…

Share

Class Constructor Function Should Do No Real Work: Getting Agile Part I

A while back I read an article by Miško Hevery that was part of a Guide for Writing Testable Code. Granted the stuff that Miško writes about is for the software engineers at Google, and my best guess is that it is primarily for Java programmers. (The examples are in Java and unfortunately [for us ActionScript 3.0 programmers] many of the solutions are through Java libraries.) Nevertheless, we can learn from the larger concepts and apply them to our projects.

Agile, Design Patterns and Unit Testing

If the senior programmers at Google (and I would imagine Adobe, Apple, Microsoft and elsewhere) have a mantra in programming, it’s probably something like this:

Keep it agile!

As most of you know (or suspect), Design Patterns are a type of Agile programming, and the development of both (DPs and Agile) in the 1990′s overlap in content and developers. They were all reading each other’s articles and contributing to one another through venues like OOPSLA and ACM (Association of Computing Machines). The agility movement was in part a reaction to heavy-handed, micro-managed systems of software development processes that were par for the course up to that time. This was not a rebellious overthrow so much as a realization that in order to get things done the processes had to change. In other words, Agile programming and Design Patterns were children of necessity as much as innovation.

The Agile Manifesto

In 2001, a number of developers put forth what they called the Agile Manifesto. It is a concise list of what they have come to value—here it is:

  • Individuals and interactions over processes and tools
  • Working software over comprehensive documentation
  • Customer collaboration over contract negotiation
  • Responding to change over following a plan

The forgers of the Manefesto go on to state that while there is value in the items on the right (normal), we value the items on the left (bold) more.

For those of you expecting something dramatic or revolutionary, you might be disappointed by this tepid manifesto. (These guys aren’t Marx & Engels even though they have PhotoShopped a picture to look like an impressionist painting of anarchists gathered in an ill-lighted London basement as they plan to overthrow the hoary capitalists). Nevertheless, you can see how such a value system is tied into a movement to get out from under the sludge dictated by a focus on protocols rather than results.
Read more…

Share
Categories: Principles

More OOP Principle Analogies

At this last OOPSLA conference I was talking with one of the European participants about remembering the different principles, and he showed me this series of images based of SOLID principles. The SOLID principles are from the acronym:

S: Single responsibility principle
O: Open closed principle
L: Liskov substitution principle
I: Interface segregation principle
D: Dependency inversion principle

My favorite is the giant Swiss Army Knife in the Single responsibility principle:

single

Now, whenever I start loading up a class with more functions than the giant Swiss Army Knife, I’m reminded to throttle back! You’ll have a lot of fun at LosTechies.com with other articles on design patterns and OOP. They’re not ActionScript, but they’re informative.

Share
Categories: Principles

OOPSLA 2009: Hope to See Some ActionScripters!

October 23, 2009 2 comments

Tomorrow morning bright and early I’m off to Orlando, Florida for the 2009 Object Oriented Programming and System Languages Association (OOPSLA) annual meetings. I’ll be making an ActionScript 3.0 presentation in a workshop on Sunday. Our workshop is named “Good Examples for Exposing Bad Practice” and meets in Pastoral 3 from 8:30-5:00 (Oct 25) Mine is based on the ‘Wrong Way Warrior”; so it should be familiar. On Monday, I’ll be at the Educators Symposium all day, and I would really like to meet other ActionScripters who might be at the conference

Here are some other speakers you might want to hear/meet:
1. Miško Hevery
Automatic Dependency Injection In The Land Of Dynamic Languages

2. Barbara Liskov (Liskov Principle)
Keynote Speaker

3. Ralph Johnson (GoF)
Regrowing a Language: Refactoring Tools Allow Programming Languages to Evolve

Anyway, just in case any of you will be there, drop by one of the sessions. Everyone’s been very accepting of ActionScript 3.0, and it’d be fun to chat with some fellow ActionScripters!

Share

Integrating design patterns "just before they become useful"

I recently commented on a provocative post by Jovan Sranojlovic called “Do Not Use Design Patterns Upfront” He made some thoughtful observations on why design patterns are important to software engineering and how they can a abused in that context as well. However, I disagreed with his basic thesis that design pattern should only be applied in a code refactoring context and not before. Based on his argument, thinking in design patterns upfront, based on the intent and purpose of code in not good, and even harmful. I tweeted my disagreement with a link to JUnit A Cook’s Tour, an example of, what I thought was, thinking in design patterns at the application design stage. The resulting tweet stream follows:

“Do Not Use Design Patterns Upfront” http://tr.im/uI3a – I don’t agree. Beck & Gamma did just that with JUnit http://tr.im/uI3z #asdp
1:09 AM Jul 30th by @chandimac

@chandimac no we didn’t. we explained junit with patterns, but we started with one tiny test and grew the whole thing from there.
6:33 AM Jul 30th by @kentbeck in reply to @chandimac

@kentbeck TX for the clarification. Do you recommend “thinking in patterns” early or should they be added at a later refactoring stage?
6:30 AM Jul 31st by @chandimac in reply to @kentbeck

@chandimac i prefer to put patterns in place just before they become useful. if i can’t see how to do that, then soon after.
6:51 AM Jul 31st by @kentbeck in reply to @chandimac

JUnit A Cook’s Tour explains the design of a system by starting with nothing and applying patterns, one after another, until you have the architecture of the system. As Kent pointed out, the article was written that way, and I had incorrectly assumed that JUnit was developed that way as well.

Design Pattern wisdom in 140 characters

I put patterns in place just before they become useful. If I can’t see how to do that, then soon after.

– Kent Beck

I was quite intrigued by Kent’s reply to my follow up question. It got me thinking about a bunch of issues. What does it mean for a design pattern to be “useful?” How much before is “just before?” What does it mean to “put patterns in place?”

I was so intrigued that I re-read a bunch of stuff on refactoring and design patterns by Beck, Gamma, Kerievsky and Alexander. I try my best to answer some of the questions raised in the remainder of this post – or more appropriately, reconcile some of my cognitive dissonance. Read more…

Share

Tight Coding and Loose Coupling

tightprogrammerTight Code and Tighter Programmers

The other day I was thinking about programs with tight code and loose coupling. Having been raised on tight coding I started looking around for a decent definition of tight code and came across one of my programming heroes, Charles H. Moore, inventor of FORTH programming language. For Moore, as well as others discussing tight code, the term refers to

… a program that is written very efficiently.

That doesn’t say a whole lot, but it says everything. In FORTH, not a single electron is wasted in the code, but not a lot of people use it because you have to think like a processing stack—last in first off. In other words, you have to think exactly backwards from normal sequencing. Ergo, most programmers have migrated to a high level languages with a C++ type of format such as ECMAScript and ActionScript 3.0. To some extent, efficient code is code without superfluous elements that gets a job done. (That’s why I don’t like to use conditional statements where I can help it—there’s generally a more direct option.)

In the context of OOP, I think that tight code can be equated with tightly woven objects. Such objects are good at what they do and nothing else. We can apply the single responsibility rule:

A class should only have a single responsibility.

However, they can work with other objects.
Read more…

Share
Categories: Principles

Wrong Way Warrior: Getting Flexibility with Design Patterns—Part II

Gentle Reader: This is the second part of a two-part set of posts. For this one to be useful, please take a look at Part I. Also, I’m not an expert on military operations or organizations; so if there’s any error in a basic infantry platoon, feel free to correct me. I am aware, however, of the 7-1 ratio of Service to Combat units in the modern military, and that this is only a simple component of a far more sophisticated structure—that’s why I selected it!

In the first installment of the Wrong Way Warrior, we saw how an OOP developer put together a simple proof-of-concept using what he thought was a prudent approach to a battle simulation. He’d provide the Warrior with certain characteristics and then subclass those characteristics to concrete warriors that would share the capabilities of the parent class. In addition, the concrete warriors would be given a movie clip representation of the warrior.

After the first design was sent to the customer, the response was less than favorable. It was described as “a children’s game” at best. The military advisor described it as a caveman battle plan where all of the combatants are similarly armed with a club to attack adversaries. The problem was that it was bound to a fairly static design, and it would be impossible to be used for a simulation that had more complex behaviors. However, the other submissions were not much better, and so the customer provided a simple organization within the military to simulate—the basic infantry platoon. After all, they’re paying your company $1.5 million to develop the simulation. (This was news to the developer!) Figure 1 shows the organization in terms of a new set of movie clips:
platoon
Figure 1: Movie clip representation of platoon
Read more…

Share

ActionScript 3.0 Design Patterns/OOP/Principles and Algorithms: The Forest and Trees of Programming

I’ve been working on documentation, and I began thinking about the concepts of design patterns/OOP/principles and algorithms as the forest and trees, respectively. The documentation involves Server Side ActionScript (SSAS, which is ActionScript 1.0) and good old ActionScript 3.0 on the client side. (In this context, client refers to the client making requests from the server, and not Client as a class that makes requests from other classes in a design pattern.)

In previous posts I’ve admitted to being an algorithm junkie, and for the last several days that’s exactly the habit I’ve been feeding. Since I was documenting SSAS—ActionScript 1.0— which has no user classes or typed data, I can say with a straight face that I really didn’t have a lot of choice. However, the client side work with AS 3.0 could have been more OOP-like and maybe a little Strategy pattern could have been used just to get everyone off on the right foot.
Read more…

Share