Archive

Posts Tagged ‘Source Code’

Customizing toString()

September 8th, 2008 11 comments

When writing classes for a framework I usually put a custom toString method into important classes so that debugging becomes easier. Normally they would go like something along the lines of:

override public function toString():String {
	return "[ClassName]";
}

… Sometimes adding properties to the returned String that give back information about the class, e.g.

override public function toString():String {
	return "[ImageClass, size=" + _size + "]";
}

But writing them rigid like that is a disadvantage when you decide later to refactor class names. Admittedly it’s also not a very elegant way so I got the idea to take the class name that is returned by getQualifiedClassName(). The only problem is that getQualifiedClassName not only provides the type name but also the whole package String of the class. Regular Expressions to the rescue! After twiddling around with them for a while (I’m by no means a RegExp expert) I got my toString method into the shape that I desired:

override public function toString():String {
	return "[" + getQualifiedClassName(this).match("[^:]*$")[0] + ", size=" + _size + "]";
}

This way it matches the String returned by getQualifiedClassName with the Regular Expression [^:]*$ which checks from the right end for an arbitrary text up to the first occurring colon, but without including the colon. Taking the first element of the Array returned by match() and you got what you need!

A nice way of using this is when writing abstract classes that contain the toString method and any subclass can use that toString method without the need to override it … that is of course unless you want ot add other output information.

ActionScript3 Dice Class

December 4th, 2007 3 comments

In game development randomness is often necessary for certain tasks, be it the random distribution of graphic tiles, a random factor in NPC AI or random stats in a roleplaying game. Especially for the latter purpose the static Dice class provides a set of methods to roll dice as it is common in a Role-playing game, to be exact four-, six-, eight-, ten-, twelve-, twenty-sided and percentile dice.

Read more…

Animated Bitmap Class

September 23rd, 2007 21 comments

The AnimatedBitmap class provides functionality for Bitmap objects that are animated by using a series of still images. When creating a new AnimatedBitmap you provide a BitmapData object that contains an image that consists of the ‘single-frame’ images for the animation.

Read more…

ActionScript 3 MultiMap Class

June 10th, 2007 9 comments

Recently I needed a HashMap for a project to map key/value pairs but in that particular case the Map required to map not just one but several values to a key. I could have used an array or object to store the values in and map that one but in practice it turned out that accessing the map looked rather messy. It would be much more elegant to have a map to that multiple values can be mapped directly. After some investigation (strangely even Java seems not to have a MultiMap included) I came up with writing my own MultiMap class, so here it is!

Read more…

Waterproof AS 3.0 Singleton

November 24th, 2006 6 comments

While reading Advanced ActionScript 3 with Design Patterns I’ve once again came across the AS 3.0 Singleton solution that has to deal with the absence of private constructors (I’ll save my rage and cursings about who had the idea to remove them for now ;)) and while the authors are using the already well known method of using a SingletonEnforcer class outside the Singleton’s package to verify that the class cannot be instanciated via the constructor they also note that this can be doublecrossed by giving null or undefined as a constructor parameter. As this is rather sub optimal I was wondering why they don’t just check inside the Singleton constructor for a null/undefined argument and throw an exception accordingly?!
I’m sure somebody else had the same idea already but here’s my idea of a waterproof Singleton class that cannot be misused from the outside (As always, if I missed any detail that accidentally breaks hell loose feel free to correct me) …

package
{
	public class WaterproofSingleton {
		static private var _instance:Singleton;

		public function Singleton(singletonEnforcer:SingletonEnforcer) {
			if ((singletonEnforcer as SingletonEnforcer) == null) {
				throw (new Error("Direct instantiation of a Singleton is not allowed!"));
			}
		}

		public static function getInstance():Singleton {
			if (Singleton._instance == null) {
				Singleton._instance = new Singleton(new SingletonEnforcer());
			}
			return Singleton._instance;
		}
	}
}

class SingletonEnforcer {}

AS3 Short Variable/Function Names vs Long Ones

August 30th, 2006 8 comments

In ActionScript it was common knowledge that shorter Variable and Function names yielded better performance in situations were it depends but does that still hold true for ActionScript 3.0? I’ve ran a couple of quick tests to find a clear answer about this. I usually tend keep my Variable/Function names to 1-3 characters when performance really mattered but it might actually not be necessary. Consider the following test …

package
{
	import com.hexagonstar.util.debug.Debug;
	import flash.utils.getTimer;
	import flash.display.Sprite;

	public class PerformanceTest extends Sprite
	{
		private var aVeryVeryLongVariableNameaVeryVeryLongVariableName:Number;
		private var num:Number;

		public function PerformanceTest()
		{
			var startTime:Number = getTimer();
			for (var i:int = 0; i < 4000000; i++)
			{
				aVeryVeryLongVariableNameaVeryVeryLongVariableName = (i * Math.random()) * 100;
			}
			var timeTaken:String = getTimer() - startTime + " ms";
			Debug.trace("timeTaken (long): " + timeTaken);
		}
	}
}

I've ran this code ten times with the 50 characters long variable name and then ten times with a 3 characters long one, both in their own SWF's. The results ranged from 757ms to 820ms, more or less the same on both sides. The sum of the long variable version was 7924ms and the one of the three characters long one was 7903ms, not much of a difference.

The next test was similar but this time with a 50 characters long Method name and the other again with a 3 characters long one, the Methods returned a random Number for 4000000 times during this test. The results looked similar but the total sum of each test gave a 12044ms for the long name test and 15570ms for the short named one. A noticable difference of over 3 seconds. This might have been coincidence but I've ran the tests a couple more times and it turned out every time that the result were very close together. This is quite interesting because I was safely believing that short names would still have an advantage. It might be time to rethink this.