Googolflex!!
  • Home
  • About
  • Contracting

Recent Posts

  • Sprint’s new “Simply ‘Almost’ Everything®” Plans
  • CSS Changes in Flex 4
  • Dotted Underline LinkButton (Flex)

About The Author : jwd

This is John Dusbabek's tech blog. John is a software engineer and Flex developer in Provo, UT, where he lives with his lovely wife and four sons.

Recent Comments

  • Nikos on Flex: Binding to an Interface
  • Iain Hosking on Apache mod_proxy_balancer: No Protocol handler was valid

Archive for Design Patterns

Aug
19

Using Bit-wise Math to Simplify Logic

Posted by: jwd | Comments (0)

Strictly speaking, bit strings are not nearly as easy to understand as named boolean variables; but there are situations when they can simplify or eliminate the need for long boolean expressions.

Consider my recent post about the ShortcutManager. There are three control keys that may or may not be pressed at any given time. This amounts to 8 possible key combinations (7 if you ignore when none of them are pressed). Here’s what this would look like if you used a boolean expression to check for each of the possible combinations:

var ctrl : Boolean = event.ctrlKey;
var alt : Boolean = event.altKey;
var shift : Boolean = event.shiftKey;

if (!shift && !alt && ctrl) {
	// CTRL
}
else if (!shift && alt && !ctrl) {
	// ALT
}
else if (!shift && alt && ctrl) {
	// CTRL-ALT
}
else if (shift && !alt && !ctrl) {
	// SHIFT
}
else if (shift && !alt && ctrl) {
	// CTRL-SHIFT
}
else if (shift && alt && !ctrl) {
	// SHIFT-ALT
}
else if (shift && alt && ctrl) {
	// CTRL-SHIFT-ALT
}

That might not seem too bad, and it isn’t that hard to understand what’s going on (even without the comments). But what happens when you’ve got 4 variables (16 possibilities)? The number of combinations increase exponentially. Even if the combinations you are actually interested in are sparse, who wants to type out 10 lines each with 32 boolean variables?

With a simple method to construct my “bit string”, we can greatly simplify this. ActionScript doesn’t have a binary number type, so you’ll have to use integers. If you can count by powers of two you won’t have any trouble. Here’s a method that constructs my “bit string” integer based on selected control keys:

private static function getFlags(event : KeyboardEvent) : uint {
	var flags : uint = 0;
	flags += (event.ctrlKey) ? 1 : 0;
	flags += (event.altKey) ? 2 : 0;
	flags += (event.shiftKey) ? 4 : 0;

	return flags;
}

Having this integer allows me to simplify the logic as follows (which isn’t harder to understand at all, if you use comments):

switch ( getFlags(event) ) {
	case 1: // CTRL
		break;
	case 2: // ALT
		break;
	case 3: // CTRL-ALT
		break;
	case 4: // SHIFT
		break;
	case 5: // CTRL-SHIFT
		break;
	case 6: // SHIFT-ALT
		break;
	case 7: // CTRL-SHIFT-ALT
		break;
}

This is powerful, but it’s just scratching the surface. I haven’t even discussed the bitwise operators &, | and ^. Or the bitwise shift operators >> and <<. These come in handy when you store a series of options as a bit string and need to test whether a certain option is on or off.

For example, if we needed to test if value returned by getFlags() had the SHIFT bit set, we could use the following boolean expression to test it. Remember SHIFT = 4:

if (getFlags(event) & 4 == 4)

Of course this doesn’t help us out much now in the ShortcutManager, but assume I was to add 3 possible contexts that these shortcuts might be used in (different screens, for example). They would hold the 8, 16, and 32 bit places. I could use bitwise math to split them if I only needed to manipulate one them at a time (a stretch, I know).

var screenOnly: uint = flags & 56;
var keysOnly: uint = flags & 7;

They have a variety of uses and are there when you need them. There’s an excellent explanation of various bitwise operations and their uses here.

Categories : Actionscript, Design Patterns, Flex 3, Flex 4, Scalability
Comments (0)
Aug
17

Flex 4 and States (they finally got it right)

Posted by: jwd | Comments (2)

I’ve finally started a serious investigation into Flex 4. Unfortunately it takes me a while to get around to these things, especially in the middle of a project with 2 developer casualties thus far. The project is winding down a bit, the interaction designers are finally off the project, and I’ve had a bit more time to turn my attention to other things. It couldn’t have happened at a better time, either, since I’ll be giving a Flex 4 presentation at the local user group meeting this coming Tuesday (specifically on the MVC changes involving Flex components).

Anyway, I just have to say I am very impressed with the new “states” implementation. Though in many ways it’s still the same old states we had with Flex 2 and 3, the approach is much cleaner and much more in line with how such a feature should be used.

What has had the greatest effect is the separation of component behavior from component appearance. With this new separation comes a much clearer understanding that states are intended to manage component state. I think this must be what the architects originally introduced states for, but because the way it was implemented this purpose was a lost somewhat.

There’s a fine line between using states as a means to add and remove children from the Application or component based on changing application state, and using them to track component state. There are occasions when application state and component state are the same thing; there are many cases when they are not. The new approach makes it much easier to handle both cases, and to know when to use states and when not to…

Define your states in the component skin, and add a corresponding SkinState metadata tag to your component class. That’s where the states belong… there should be no need to have states or use the currentState property in your component class, though it inherits it from UIComponent.

Based on your data model, or user gestures, you should rely on one of the skins states (or a separate skin altogether) to change the view to match the state. There’s a method called getCurrentSkinState() where this can be handled, and it will be called after invalidateSkinState() is called (perhaps inside commitProperties().

In conclusion, though the nasty, nasty states syntax will become history, states should still be used judiciously.

Categories : Actionscript, Architecture, Design Patterns, Flex 4
Comments (2)
Jul
25

Detecting Changes in an Object

Posted by: jwd | Comments (0)

One of the projects I’m working on right now requires me to detect when changes to an object have occurred, so as to enable or disable some “OK”, “Apply” and “Cancel” buttons in the appropriate context.  For the longest time I’ve been thinking I was going to implement this with some sort of data binding, but as it’s distilled on my mind over the past few weeks I’ve decided that wasn’t the right approach.  Here are a few of the requirments/factors that played into that decision:

Background info: the gist of this app is that there’s a datagrid whose items can be loaded into a dialog for editing.

  1. The changes don’t affect the actual object in the model or database being edited until “Apply” or “OK” is pressed (i.e. they can always cancel out of the operation, regardless of any changes)
  2. If a user edits a field, I want that to register as a change.  If they change the field back to what it was, I don’t want that registered as another change, it needs to be as if it had never been changed (i.e. “OK” is not enabled).  This is why I ruled out a Binding approach.
  3. The objects being compared are pretty complex objects.  I didn’t want to have to go and manually compare each property, the properties of composed objects, and the properties of objects nested in collections.  The time to implement this, and the amount of time it would take to compare the object with its sentinel after each edit seemed to rule this option out.

I became pretty familiar with ByteArrays last year during a computer security class (I implemented my AES, RSA, etc. labs using ActionScript) and so I got the idea of serializing these objects to a ByteArray, and then comparing them.  After I came up with the idea, I googled it and realize I’m hardly the first to come up with it, but I’m still going to share it.

First, I built a method to convert an object to a ByteArray, convertToBytes:

public static function convertToBytes(m : Object) : ByteArray {
   var ba : ByteArray = new ByteArray();
   ba.writeObject(m);

   return ba;
}

The ByteArray class has lots of useful writeXXX methods depending on what you’re doing. In this case we use writeObject() which serializes an object to AMF, and writes it to the ByteArray.

Second, I built a method that compares two ByteArrays. There are several ways that this can be accomplished, I chose straight iteration. If someone knows a faster way, please let me know. The faster the better. Here it is:

public static function isByteArrayDifferent(base : ByteArray, revision : ByteArray) : Boolean {
   if (base.length != revision.length)
      return true;
   for (var i : int = 0; i &lt; base.length; i++) {
      if (base[i] != revision[i])
         return true;
   }
   return false;
}

Obviously, if they are different lengths they’re not the same. I like that the method short circuits if a difference is detected, which will be the most common case.

Finally, I wrote the method that accepts the two objects, and returns a Boolean indicating whether a change has been detected. It’s simple, as the preceding two methods do all of the work.

public static function hasObjectChanged(a1 : Object, a2 : Object) : Boolean {
   return isByteArrayDifferent( convertToBytes(a1), convertToBytes(a2) );
}

And it works pretty well. There are a few gotchas I will point out, fortunately none of them apply to my application specifically.

First, suppose your object has a collection with two objects, 1 and 2. The order matters when the objects are serialized. An object with 1,2 will serialize differently than the same object with 2,1. Depending on your application you may have to handle this case specially (if 2,1 is considered the same as 1,2).

Second, you can’t use this method to tell if two objects are the same instance in memory. There are other ways of doing that, this isn’t one of them.

ByteArrays are very useful and have loads of other applications (see the ObjectUtil.copy() method to see how to make copies of objects using ByteArrays. I’ll include a quick method I threw together to output the contents of a ByteArray (it’s very similar to isByteArrayDifferent(), in case anyone’s interested. I used it for debugging, but it can be easily modified to return the String instead of outputting it.

public static function outputBytes(label : String, block : ByteArray) : void {
   var s : String = &quot;&quot;;
   for (var i : int = 0; i &lt; block.length; i++) {
      s = s + uint(block[i]).toString(16) + &quot; &quot;;
   }
   trace (label + &quot;: &quot; + s);
   trace();
}
Categories : Actionscript, Design Patterns, Flex 3
Comments (0)
Oct
13

Book Review: Head First Design Patterns

Posted by: jwd | Comments (0)

Head First Design Patterns by Eric and Elizabeth Freeman was great.  The designers of the series really tout their method of presenting the material as being on the cutting-edge, and although I can’t speak for everyone, the the content really got through to me.

I took a class a few semesters back that had design patterns as a core part of the curriculum, and it really opened my eyes as far as software development goes.  We used the GoF book as our text, which is a very thorough, technical book that I have often been thankful to have in my personal library.  I can’t deny that it comes up pretty dry when you’re trying to wrap your mind around a design pattern for the first time.  There were a few design patterns we studied in the class (out of a total of about 20) that I left without having grasped well enough to where I felt I could apply it in real project (specifically the incarnations of the Factory patterns, with the exception of a simple factory).

The treatment of these patterns in HFDP really helped clear up a lot of the points I had struggled with before.  Reading about the patterns I felt I understood already gave me an even better understanding.  And the book is quite enjoyable, I’m not usually able to read “tech” books word for word.

I recognized a lot of the examples my professor used in class (which he borrowed from HFDP), and I remember him mentioning the book once or twice.  I wish he had recommended it, because I probably would have benefited from it sooner.

At any rate I highly recommend this book, and will definitely try out a few more books from the series.  I’ve already ordered HF Object-Oriented Analysis and Design, and HF Software Development (two other topics I “already know about”).

Categories : Book Reviews, Design Patterns
Comments (0)
May
08

Flex: Binding to an Interface

Posted by: jwd | Comments (11)

We recently ran into a problem using our TrueMVC framework (which prescribes coding models to an interface and binding directly to the models) in that it was not obvious how to make the properties (getters/setters) of an interface bindable.

Consider the following interface:

package model {
  public interface ISimpleModel {
    function get name() : String;
	function set name(v : String) : void;
  }
}

Having the following implementation:

package model {
  public class SimpleModel implements ISimpleModel {
    private var _name : String = '';    

	public function SimpleModel() {}       

	public function get name() : String { return _name; }
	public function set name(v : String) : void {
	  _name = v;
	}
  }
}

Our goal is to bind to the name property of type ISimpleModel. If we add the [Bindable] tag above the get function declaration in the interface we get the error message:

[Bindable] not allowed on global or package-level functions

If we add the [Bindable] tag above the get function definition in the implemtation, or if we use no [Bindable] tag at all (except above our various model instances) then we get a warning:

Data binding will not be able to detect assignments to "name"

Which when executing the code, we observe to be correct.

To get binding to work correctly, you should declare the interface bindable like this:

[Bindable]
public interface ISimpleModel {
  .
  .

And then either declare the implementation class, or specific getter/setter pairs bindable. The warnings and errors go away, and the bindings will work.

Download the poorly commented source for this post here.

In the comments below, Alex Uhlmann suggests using a named Bindable metadata tag on the accessor in the interface.

package model {
  public interface ISimpleModel {
    [Bindable(event="propertyChange")]
    function get name() : String;
    function set name(v : String) : void;
  }
}

There should be a corresponding Bindable metadata tag in the implementation, although the event name doesn’t have to be manually specified again. This is the solution we originally wanted since it allows us to avoid class-level binding in cases where we only want property-level.

Categories : Actionscript, Design Patterns, Flex 2, Flex 3, MTC Framework, TrueMVC
Comments (11)
Apr
30

TrueMVC Framework

Posted by: jwd | Comments (1)

At the organization where I work we are currently building a general purpose framework for Adobe Flex / AIR applications.  We do a lot of Flex development there, and have done several large projects based on Cairngorm.  It wasn’t working out for us for a couple of reasons, primarily because:

  1. There was a large chunk of code that had to be included.  If this weren’t bad enough, the user needs to have a fair knowledge of this code (as many classes are extended to make use of the framework’s features).
  2. The learning curve is quite steep, and assumes a basic understanding of several design patterns (especially if you need to create workarounds in areas the framework fails your project).
  3. A large majority of the development staff are students, and therefore we experience an above average turnover rate compared to the industry as a whole.

Any one of these might not seem so bad, but taken as a whole we needed something simpler.  Something with little or no code to extend, and a few basic patterns that could be taught as “conventions” rather than patterns.  TrueMVC is (or will be) the result of these efforts.  I don’t have a link at the moment to the documentation

The basics of it are as follows:

  1. All models implement an interface.
  2. All views bind to the model (which is in fact an instance of ISomethingModel).
  3. All controllers have the same name as their respective views appended by the suffix “Controller“.
  4. Controllers reside in the same folder as their views, and are included in the view using a <Script source="" /> tag.

It makes heavy use of binding, in fact the views should only be updated via their bindings to the model (i.e. as per the Model-View-Controller pattern).  And that’s pretty much it.  We’re in the process of implementing an Active Record-like data object, which will be the only code artifact of the framework (and won’t be necessary, strictly speaking as long as any other data retrieval mechanism gets data and sticks it in the model).  There’ll be a separate post about that.

Categories : AIR, Actionscript, Architecture, Cairngorm, Design, Design Patterns, Flex 2, Flex 3, Frameworks, MTC Framework, TrueMVC
Comments (1)

Search

Feedburner

Subscribe to

Get the latest updates delivered via email

Calendar

September 2010
M T W T F S S
« Jul    
 12345
6789101112
13141516171819
20212223242526
27282930  

Archives

  • July 2010 (1)
  • June 2010 (2)
  • May 2010 (1)
  • February 2010 (11)
  • January 2010 (3)
  • December 2009 (5)
  • November 2009 (1)
  • August 2009 (8)
  • July 2009 (8)
  • May 2009 (4)
  • April 2009 (1)
  • March 2009 (6)
  • January 2009 (1)
  • November 2008 (4)
  • October 2008 (5)
  • September 2008 (1)
  • August 2008 (5)
  • July 2008 (1)
  • June 2008 (2)
  • May 2008 (8)
  • April 2008 (5)
  • March 2008 (2)
  • February 2008 (3)
  • January 2008 (1)
  • December 2007 (6)
  • November 2007 (9)
  • October 2007 (1)
  • September 2007 (2)

Categories

Tag Cloud

adobe apache Architecture book review C++ centos client server architecture Custom Components database Design error message fedora flash catalyst flex Flex 3 Flex 4 fms iis 6 Interaction Design load balancing master-master master-slave mod_proxy_balancer Monkey Patching MySQL no protocol p2p peer to peer Perl PHP Red5 regex replication self registration selinux Shell Scripting shortcut manager skins socket policy file sockets states stored procedures stratus tools workflow

Coworkers

  • Casey Jackman
  • Sean Murphy

Family

  • Emily & CJ
  • Family Blog
  • Gary Dusbabek

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

RSS FlexExamples

  • Styling the text selection format on a Spark TextArea control in Flex 4
  • Setting the scale mode on a Spark Image control in Flex Hero
  • Setting the fill mode on a Spark Image control in Flex Hero
  • Setting a bitmap image fill on a Spark Form container in Flex Hero
  • Setting a bitmap image fill on a Spark FormHeading control in Flex Hero

Spam Blocked

847 spam comments
blocked by
Akismet

Sponsored Links

JUICE Chat

BYU Adobe Users Group


Copyright © 2010 All Rights Reserved
Flexx Theme by iThemes
Powered by WordPress