Posts Tagged ‘class’

Switch-case for object’s class type

Friday, August 31st, 2012

Quick tip; instead of using a bunch of “if (x is y) else if (x is z) else” conditionals, you can simply get the class of any object using the “constructor” property. It’s not exposed trough strict typing though, so you have to typecast your instance to Object to access it.

This allows you to have a switch-case for an object’s class:

function addShape(shape:Shape):void {
	switch (Object(shape).constructor) {
		case Circle:
			trace("It's a circle");
			break;
		case Square:
			trace("It's a square");
			break;
		default:
			trace("Unknown shape");
	}
}

Prefixing private variables with an underscore in AS3

Tuesday, April 26th, 2011

A coworker and I had a discussion about using underscores for private variables in AS3.
I’ve always added an underscore before my private variables, like so:

private var _myVariable:int;

While he wanted to only use underscores for when you have a variable which has a getter/setter:

private var _myGetAndOrSetVariable:int;
private var myPrivateVariable:int;

public function get myGetAndOrSetVariable():int {
	return _myGetAndOrSetVariable;
}

This was a little alien to me and I didn’t get the point of it. Why should you only sometimes use an underscore? He answered that then you know that private variable has a getter/setter if it has an underscore.

Well, that’s not a bad reason. I googled around and it sounds like Adobe actually enforces this kind of rule in their Coding Conventions document; “Give the storage variable for the getter/setter foo the name _foo.”.
They don’t say anything about if the other variables shouldn’t have underscores though, so I dived into the source code of the Flex SDK to see what they were using.
Turns out, both! In some classes every single private variable had an underscore, and in other ones only variables with a public getter/setter had one.
In this poll, majority of AS3 developers always use underscores.

I thought long and hard, and I came up with these reasons for why one should always use underscores for private variables:

  • It can be confusing “sometimes and sometimes not” putting an underscore.
  • You can see immediately if the variable is accessible to another class when you always prefix private variables with underscores.
  • Most of the in-house code and frameworks always use underscores (consistency).
  • Pressing ctrl+space for IDE code completion shows you all the local private variables if you type an underscore first, if you don’t you get every single variable in the class with every class in the project together in one gigantic list.
  • Most other coders and their frameworks online use it.
  • If you are going to create a getter/setter for the variable, you have to rename it first to include the underscore.
    • Also, if you rename it without refactoring, all references in the class will now pull from the getter (possible calling extra code) when maybe they were only supposed to get the raw data.
  • If the other method is used I will know much less about the variable just from looking at it, possible making debugging harder. It could be a local variable, a class function, a function parameter, a private variable without a getter/setter, a getter/setter function or a public variable.

Personally, I don’t really care when I’m writing code in a class if a variable has a getter/setter. That’s encapsulation, and I think mostly of it when working in/thinking of other classes that interact with the current one. I much more care knowing if I’m working with a variable or calling a getter function (it could be a public variable too, but still less complicated).
I also prefer to write “_id = id” instead of “this.id = id”.

Also, adding an underscore just to avoid a name conflict doesn’t sound proper to me. It sounds like you had to make a workaround to make the code do what you want (read: a shit mix).

So far these are enough reasons for me to stick with prefixing my private variables with underscores. I have an open mind though, a comment can easily change my mind if it has the right arguments.

What is your method, and why? Please do share =)

Preloader without a loader-swf in AS3

Wednesday, November 17th, 2010

Here’s one method of loading your AS3 movie, using a preloader class that loads before all other classes.

The flex compiler can actually split up the code for you so one class loads before all others. Even though we’re using the flex compiler to do this we do not have to have a Flex project, it can be a Flash project or a pure actionscript project. If we’re using a Flash project we do have to set the flex compiler path though.

Anyways, the way it works is that in your main class you add the Frame metadata, like this:

package com.flassari {
// Preloader meta tag
[Frame(factoryClass="com.flassari.Preloader")]
// Start of our own application code
[SWF(backgroundColor="#FFFFFF", frameRate="24", width="800", height="600", pageTitle="My preloaded project")]
public class Main extends Sprite
{

The preloader has to extend movieClip, because behind the scenes it is using frames for its magic.
In your preloader class, when it is done loading (by checking if it is at the last frame), your have to instantiate the main class with no strict typing. If you were to use strict typing, the whole application would have to load before the preloader can be shown so that would defeat the purpose of a preloader:

private function onEnterFrame(e:Event):void {
	if (currentFrame == totalFrames) { // If we're at the frame where Main is ready
		// Stop and clean up
		stop();
		removeEventListener(Event.ENTER_FRAME, onEnterFrame);
		// Create the main application and add it to the display list
		var mainClass:Class = getDefinitionByName("com.flassari.Main") as Class;
		addChild(new mainClass() as DisplayObject);
	}
}

Just remember, everything that the preloader references will be loaded before the preloader can be shown, so keep it to a minimum.
Also, because the main class is created before it is put on the stage, be sure not to reference the stage in the constructor.

Color.setTint() alternative (AS3)

Monday, February 1st, 2010

I once discovered a really cool feature of the color class that lets you set the tint of an object via its color transform object using the setTint function.
The bad news though is that the Color class is in the fl namespace, so if you’re developing outside of the Flash IDE you have no access to that class natively, so here is how to replicate that functionality without the Color class:

Tinting with the color class:

import fl.motion.Color;
// Tint the movie clip 50% with the color 0xFF9933
var c:Color = new Color();
c.setTint(0xFF9933, 0.5);
myMovieClip.transform.colorTransform = c;

Tinting without the color class:

import flash.geom.ColorTransform;

// Tint the movie clip 50% with the color 0xFF9933
var tintColor:uint = 0xFF9933;
var tintMultiplier:Number = 0.5;
setTint(myMovieClip, tintColor, tintMultiplier);

function setTint(displayObject:DisplayObject, tintColor:uint, tintMultiplier:Number):void {
	var colTransform:ColorTransform = new ColorTransform();
	colTransform.redMultiplier = colTransform.greenMultiplier = colTransform.blueMultiplier = 1-tintMultiplier;
	colTransform.redOffset = Math.round(((tintColor & 0xFF0000) >> 16) * tintMultiplier);
	colTransform.greenOffset = Math.round(((tintColor & 0x00FF00) >> 8) * tintMultiplier);
	colTransform.blueOffset = Math.round(((tintColor & 0x0000FF)) * tintMultiplier);
	displayObject.transform.colorTransform = colTransform;
}