<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>dispatchEvent() Blog™ &#187; oop</title>
	<atom:link href="http://dispatchevent.org/tag/oop/feed/" rel="self" type="application/rss+xml" />
	<link>http://dispatchevent.org</link>
	<description>Collective thoughts on the Flash Platform, iOS, Unity, and any other technology we use.</description>
	<lastBuildDate>Tue, 17 Aug 2010 08:15:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Q&amp;A &#8211; is, as, and type conversion</title>
		<link>http://dispatchevent.org/mims/is-and-as/</link>
		<comments>http://dispatchevent.org/mims/is-and-as/#comments</comments>
		<pubDate>Tue, 27 Jan 2009 07:41:08 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[AS3]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tips, Tricks, and Hacks]]></category>
		<category><![CDATA[as]]></category>
		<category><![CDATA[coercion]]></category>
		<category><![CDATA[cs]]></category>
		<category><![CDATA[downcasting]]></category>
		<category><![CDATA[is]]></category>
		<category><![CDATA[lesson]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[types]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=591</guid>
		<description><![CDATA[A question from a reader gave me an excuse to write a huge rant about type conversions: I&#8217;m doing a little exercise in a book that makes a textfield in which each letter can only be entered once. Not very &#8230; <a href="http://dispatchevent.org/mims/is-and-as/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A question from a reader gave me an excuse to write a huge rant about type conversions:</p>
<blockquote><p>I&#8217;m doing a little exercise in a book that makes a textfield in which each letter can only be entered once. Not very useful, more of a teaching thing really. However there&#8217;s a bit of code that says:</p>
<p><code>var tf:TextField = event.target as TextField;</code></p>
<p>I don&#8217;t understand this at all! What the hell is <code>event.target as TextField</code>? Anyway here&#8217;s the full code for context&#8217;s sake:</p>
<pre lang="actionscript3">
package com.FoundationAS3.ch6 {

	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.events.TextEvent;

	public class PreventDefaultTest extends Sprite {

		public function PreventDefaultTest() {
			var tf:TextField = new TextField();
			addChild(tf);

			tf.width = stage.stageWidth;
			tf.height = stage.stageHeight;
			tf.type = TextFieldType.INPUT;
			tf.wordWrap = true;

			tf.addEventListener(TextEvent.TEXT_INPUT, onTextFieldTextInput);
		}

		private function onTextFieldTextInput(event:TextEvent):void {
			var tf:TextField = event.target as TextField;
			if (tf.text.indexOf(event.text) &gt; -1) {
				event.preventDefault();
			}
		}
	}
}
</pre>
<p>Thanks,<br />
-Neal
</p></blockquote>
<p>My response after the jump.<br />
<span id="more-591"></span><br />
Neal,</p>
<p>First of all, let me say that preventing the default event handler, e.g. for a <code>TextField</code>, is rarely used and isn&#8217;t worth spending a lot of time discussing.</p>
<p>On the other hand, the <code>as</code> operator (along with the <code>is</code> operator and the type cast) are totally useful and you should learn all about them. First, let me cover <code>is</code>:</p>
<h3>is</h3>
<p><code><a href="http://livedocs.adobe.com/flex/2/langref/operators.html#is">is</a></code> is an operator that evaluates whether some object <em>is</em> of a certain type. The syntax is <code>[object] is [type]</code>. The term &#8216;type&#8217; is similar but not interchangeable with &#8216;class&#8217;. A type can refer to not only the class of an object, but also the super-classes it extends and interfaces it implements. An example:</p>
<pre lang="actionscript3">
var sprite:Sprite = new Sprite();
trace(sprite is Sprite); // true, because the sprite object is an instance of Sprite
trace(sprite is DisplayObject); // true, Sprite is a subclass of DisplayObject
trace(sprite is MovieClip); // false, MovieClip is a subclass of Sprite.
trace(sprite is IEventDispatcher); // true, DisplayObject extends EventDispatcher which implements IEventDispatcher.
</pre>
<p>Note that sprite is not a MovieClip but a MovieClip is a Sprite. Because MovieClip extends Sprite and contains all the same methods and properties as Sprite but not the other way around. </p>
<p>Note: the <code>instanceof</code> operator commonly used in AS1/2 still exists in AS3 but is for all practical purposes deprecated by <code>is</code> (although still useful if you&#8217;re manipulating prototypes). <code>typeof</code> is also related but shouldn&#8217;t be used in place of <code>is</code> because it only returns strings for primitive data types like Object and String. In order to get the actual name of the class that an object is an instance of, you can use the <code>flash.utils.getQualifiedClassName()</code> global function.</p>
<h3>as</h3>
<p><code><a href="http://livedocs.adobe.com/flex/2/langref/operators.html#as">as</a></code> functions similarly to is except that it actually will attempt to coerce the object into the data type that you ask for. <a href="http://en.wikipedia.org/wiki/Type_conversion">Coercion</a>, AKA type conversion or casting, is the act of changing the data type of an object. </p>
<p>With the case from your book, an <code>Event</code> object has a <code>target</code> property which refers back to the object that originally dispatched the event. Since the <code>Event</code> object is designed to be sent out from all different types of objects, the target&#8217;s data type is <code>Object</code> (the mother of all the other classes). So, if the variable you&#8217;re defining is a TextField, you&#8217;re expecting an object with a <code>text</code> property. <code>Object</code>, doesn&#8217;t have a <code>text</code> property so you have a dilemma. The solution is to cast the object into the type you want it to be, basically forcing it to be more specific.</p>
<pre lang="actionscript3">
var textField:TextField = event.target; // Throws compile error because target is an Object not a TextField

var textField:TextField = event.target as TextField; // OK! as long as the event target actually is a text field
</pre>
<p>Going from a more generic type to a more specific type is called a <em>downcast</em>. Going from a more specific type to a more generic type is called an <em>upcast</em>. Upcasting in ActionScript, as with most other languages, is done automatically and is always safe. e.g. a Sprite can be used as a parameter for a function that requires a DisplayObject. Downcasting on the other hand is unsafe meaning that you can&#8217;t always guarantee that it will work. A DisplayObject is not necessarily a Sprite. </p>
<p>When an attempt to downcast with <code>as</code> fails, the value returned will be <code>null</code>:</p>
<pre lang="actionscript3">
var string:String = new String();
var textField:TextField = string as TextField // string can't be converted. textField will be set to null
</pre>
<p>If you&#8217;re not sure whether your object is the right type (and you should never assume it is) check to see if the value is null before proceeding:</p>
<pre lang="actionscript3">
var typedObject:TypedObject = mysteryObject as TypedObject;
if (typedObject != null) {
	// conversion was successful! do something with typedObject
} else {
	// conversion failed
}
</pre>
<h3>Type casts</h3>
<p>Another way to do this with slightly different results is by type casting. Type casting works with the syntax <code>Type(object)</code> and is functionally similar to <code>object as Type</code>. The only difference is with a type cast, you get a runtime error if the coercion fails.</p>
<p><code>var textField:TextField = TextField(event.target); // if event.target is a TextField, you're good. If not, you get an error.<br />
</code></p>
<p>you can also shortcut like this:</p>
<p><code>TextField(event.target).text = "foo";</code></p>
<h3>Conclusion</h3>
<p>Why are objects like <code>event.target</code> given such generic data types? The idea is that you want to minimize the requirements of a property, parameter, or function to maximize the number of objects that will qualify thus making your program more flexible. In other words, strive to use the most broadly defined data types that you can get away with. </p>
<p>For example, say you&#8217;re creating a simulator program for getting a person from their home to their job. You may be tempted to define your <code>modeOfTransportation</code> variable with a type of <code>Car</code>. But down the road the company you&#8217;re working for wants to create a more green image for themselves and suggests using alternative modes of transportation. If you&#8217;re code is based on Car, it&#8217;s limited in what you can do with it. However, if you had used a <code>Vehicle</code> type (includes Car, Bike, Motorcycle, Donkey) instead, you may not have had a problem. Using interfaces like <code>IConveyance</code> makes your program even more flexible because you can include non-vehicluar objects like MolecularTransporter, Feet, and CrowdSurfing as long as they satisfy the interface. In fact, I would suggest as an experiment that the next time you start a project, try coding all the interfaces first before you move on to coding specific classes. You&#8217;ll be surprised at how flexible it is and how it forces you to consider the roles of your classes from a higher level. </p>
<p>Though you should strive for generic types, sometimes you will need to get specific. If your program has a gas station simulator in it, the <code>fillTankOfVehicle()</code> method might require a <code>MotorVehicle</code> class (includes Car, Motorcycle, Plane) instead of simply <code>Vehicle</code>. Still, you should only get very specific when your program requires it. If you are making a racing program, use <code>F1RaceCar</code> only when a simple <code>Car</code> won&#8217;t cut it.</p>
<p>I hope this helps! This is definitely a difficult topic even for experienced programmers to grasp!</p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/is-and-as/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
