X Gems of AS3 Language Design

Tue, 05/04/2010 - 23:05 — Boris

Ok, so AS3 has its fair share of problems. It is slow, it has next to no support for templates/generics and somewhat sparse standard library. And yet still I love using it.

Why? It has managed to pull together some of the rarer features that I think every language should have. Language designers, take note of the following.

Easy to parse

Better known in: Pascal, Ada
Worst offenders: C++, Java C++ for consistently bad decisions and Java for copying them

A lot of languages fall into the C trap of declaring variables, function parameters, members, like this:

Type myInstance;

This is a horrible convention. When the parser comes across the "Type" token, it doesn't know what it is until later, and in some languages, needs higher level semantic information to decide. It gets even worse when declaring functions. It is also not so readable imho. AS3's

var myInstance:Type;

is much simpler.

Same thing goes for templates, using Template<templateArg> is a recipe for parsing nightmares, as it is just to easy for those angle brackets to be comparison operators. The addition of a dot, Template.<templateArg>, and it is suddenly easy. (though still not perfect)

Modern Primitives

Better known in: Javascript
Worst offender: Lua Lua cannot even manage ints or arrays, let along regexps

AS3 has regexps and XML as basic primitives. These are so commonly used in languages, and yet working with them is frequently cumbersome. Regexps require escaping, and often don't mesh with the standard library, while XML becomes huge fests of method calls and nested loops, or (shudder), visitor patterns.

AS3 has regex literals, which can slot into most string manipulation functions, XML literals that can be escaped back to AS3 code to embed variables and the like, and most importantly, E4X, which I cannot do justice in a quick synopsis.

First class functions and lambdas are also a needed primitive, but I think most language designers have caught onto that one now.

Actions speak louder than louder than words, so here is some AS3 versus Strawmania, a language I just made up for comparison. It's actually being generous, there are languages out that that fail far harder at these toy examples.

Actionscript Strawmania
function upper(c){return c.toUpperCase();}
"the quick brown fox".replace(/\b./g, upper);
// The Quick Brown Fox
text = "the quick brown fox";
atStart = true;
for(i in 0...text.length())
{
  if(atStart) text[i] = text[i].toUpperCase();
  atStart = text[i]==" ";
}
// The Quick Brown Fox
function toXML(circle)
{
  var x = 
            
              {circle.color.toString()}
            
          ;
}
function toXML(circle)
{
  var x = XML.makeElement("circle");
  x.setAttribute("radius", circle.radius);
  var color = XML.makeElement("color");
  color.appendChild(XML.makeText(
    circle.color.toString());
  x.appendChild(color);
}
var maleMiddleNamesStartingWithJ = 
  familyTree..person.(@gender == 'M').
  (middleName.toString().match(/^J/));
results = [];
for(var p in familyTree.descendantsByName("person"))
{
  if(p.getAttribute("gender")!="M")
    continue;
  var middleName = p.getElement("middleName").text();
  if(middleName[0]!="J")
    continue;
  results.push(p);
}

AS3 actually takes XML integration one step further that all members of a class are associated with a namespace, which is cool, but not imho useful enough to merit this list.

Implicit method binding

Better known in: Python?
Worst offender: C++98 Ever tried boost::bind ?

This one is so simple I don't know why more languages don't do it. If you get a method from a instance of a class, it is implicitly bound to that instance.

var a:Array = [1,2,3];
var f:Function = a.join;
f(","); // 1,2,3
f(" "); // 1 2 3

This turns out to be vitally useful for event systems. Want to connect button A to oojamaflip B?

buttonA.addEventListener(Event.PRESS, oojamaflip.flipOut);
// Later...
buttonA.removeEventListener(Event.PRESS, oojamaflip.flipOut);

No bind statements, no lambdas, just what you need. Note how I didn't need store a variable during the add phase that I needed to pass to the remove phase.

Optional Static Typing

Better known in: Implicitly typed languages
Worst offender: Java No typedefs + generics

AS3 (& haXe) seems to be more or less unique in this feature. Variables etc can be either typed or untyped, with casts added for you beneath the hood. I really like the way you can write something quickly, with that untyped scripting language feel, and then neaten it up by adding static typing, to enhance readability, code completion and documentation.

Once again, AS3 falls down in practice - I statically type everything for the performance gain, except the areas where you are forced into dynamic typing - mainly when using Function.

Conclusion

I'm not saying AS3 is an amazing language. I'm not saying your language sucks (though it does - the perfect language has yet to be made). I am saying there are some under-appreciated ideas here, which I hope to see more of in the future. I'm looking at you, Javascript and Python.

Post Script

I don't know much about Ecmascript, but I'm guessing that the designers of it are responsible for many if not all of the inovations seen here, so props to them.

Also, sorry if I didn't represent your language, I appreciate there are many so alien from the "common set" that a lot of the points here are irrelevant. Who needs weak typing when you have Haskell's all powerful type inference, or regexp literals when you have Scheme's reader macros?


fter you have decided to

fter you have decided to consider law education as a career after completing your graduation there are two things to be considered even then. www.kochlawfirm.org


I grew up in the 1980s when it seemed that everyone wanted to be a lawyer like the ones on LA Law. www.criminallawfirm.org


Car buying has grown simpler by the time due to growth of car finance schemes. Financing your car appropriately takes into account your financial conditions and repayment capacity before giving you a car finance loan. www.wolffinance.org


Considering failure is valuable, though, because the very ingredients that make for business failure can be transformed into business success. www.businessformations.org


During the 2000s, business planning and entrepreneurship experienced a resurgence due to the massive and expansive growth of Web 2. 0 businesses and the solid GDP growth of the US. www.businessvids.org


Having the potential to turn the sails in favour of neophytes and bring down incumbents, Digital Disruption is reshaping markets with the speed and force that has no match in history! Survivors are those businesses that are pro-actively adopting digital, but in order to thrive, they must also innovate new business models to keep pace with the digital age! www.businessitonline.org


A general conception among the consumers is that cheap health insurance should not be costly-the cheapest health insurance plan available in the market is their target. www.help-health.org


In the last few months there have been many Health Care Reform rules and regulations updated by the Health and Human Services Department. www.healthlawbenefits.org


Health, good or bad, is too often something that happens TO people. This article offers an alternative way to view health, as either static or earned. www.questionmyhealth.org

Beauty is everywhere if we would only care to look with spiritual eyes. What often escapes the mind is what the heart cannot ignore, for as the heart is beautiful, so is this what it is able to recognize and appreciate perfectly. reflectionsofbeauty.net


On the different theories of beauty and the role of perception in the judgment of beauty. The psychology of beauty is complex not just because the concept of beauty is as yet undefined but also because it is largely true that beauty lies in the eyes of the beholder or how individuals perceive other people or things. goodgoshbeauty.net


Your Indian marriage proposal or matchmaking has taken place. You know that the next step is planning your Indian wedding, but where do you start? Read on further to discover what will be the next steps to take to prepare for your wedding. weddingwhisperers.net


Let us help you explore Australia to find the perfect wedding venue for your ceremony and reception. Whichever location you choose you can rest assured that you and your guests will experience a wealth of fantastic scenery, blue skies and hours of sunshine downunder! bornwedding.net


Getting your wedding gown cleaned and preserved as soon after your wedding as possible helps to give you the very best possible results. You can still have your gown cleaned and preserved years later, but the delay can cause problems. Which of the three wedding gown preservation methods is best? smithfieldweddings.net


Higher education in India has entered into a new phase with the invasion of foreign universities and increasing aspirations of Indian students. gladstone-education.net

Health, good or bad, is too

Health, good or bad, is too often something that happens TO people. This article offers an alternative way to view health, as either static or earned. www.hygieiahomehealth.net


How often do you look in the mirror and say "If I could just lose ten pounds, then I would be happy"? Unfortunately, the majority of American women and girls are dissatisfied with their bodies, and many take extreme measures in an attempt to change their bodies. www.healthybodyz.net


Your computer is hacked? what to do now? Here are the steps to take if your computer is victim of a hacker. www.hack4health.net


here is so much information available on the internet right now regarding travel. There are online travel sites for cruises, hotels, air, trains and any other type of travel. www.anyminutetravel.net


There is no dearth of travel enthusiasts in India. Most Indian travelers prefer international destinations to spend their holidays. www.travelno1.net


Car finance has become big business. A huge number of new and used car buyers in the UK are making their vehicle purchase on finance of some sort, and many people choose to arrange it through the dealership. www.greendealfinance.net


we are beginning to witness a change in how business owners access finance with many now actively seeking out alternative sources. www.financeplanet.net


Talk to any business owner or read the business section of any newspaper and you're likely to come across stories of struggles to access sufficient finance to grow or maintain their business www.thebusinesshive.net


Businesses are looking for opportunities to obtain alternative financing in the face of the dwindling lending appetite from banks. www.myrealbusiness.net


Are you having a financial business website? Are you happy with the return of your investment in developing the website? I mean to say is the site focused to showcase your business? www.connectbusinesses.net


Financing a small business can be most time consuming activity for a business owner. It can be the most important part of growing a business, but one must be careful not to allow it to consume the business. www.mybusinessmarketing.net


This article discusses issues with popular home search sites and how they can add unnecessary stress to the home buying process www.helpusbuildhomes.org


Why it is Important for you to know, understand and follow the 10 complete steps to the home buying process in most states. www.princetonhomes.org


The universe that we are living in is governed by universal laws. This law is something that works the same in an orderly manner for every person at anytime. www.lemon-law.org


So you're an aspiring law student, hoping to get into the best law school. But you wonder: which undergraduate courses should you take to get into law school? Read on and we'll fill you in! www.800laws.org

Informative post

Significant data and magnificent configuration you got here! I might want to thank you for offering your considerations and time into the stuff you post!! website design company in Delhi

interesting

I've done my fair share of programming in the past, this post gets me back into the mood, although I fully enjoy doing my diagnostic and repair work over on my site, I think I enjoy putting a post like fixing Winsock errors, over writing code for a program.

This article is by far the

This article is by far the interesting one I have ever come across. Great theory and presentation.

amazon tom cruise

hiii there

umsonnst chatten Webcam Cam Chat 19

chat, XXX, Livecam

Reply to comment | www.boristhebrave.com

If you would like to obtain a good deal from this article then you have
to apply such techniques to your won weblog.

good good work

good good work

xsvbxfcbvcx

xsvbxfcbvcx

Hey, Interesting article,

Hey,

Interesting article, I've been doing a bit of AS3 and trying to get to grips with it. Some interesting points made here about the speed.

Regards

Loz.
- stopzilla review

Hello there, can I republish

Hello there, can I republish this on my site if I link back to your site? - ways to lose weight fast and free

Thanks for your interest (and

Thanks for your interest (and your conscientiousness), but no. Link's just work fine.

"AS3 is slow" - Compared to

"AS3 is slow" - Compared to JS it definitely isn't...

"I statically type everything for the performance gain" - Unfortunately, you'll get a perfomance hit if you statically type everything...
http://blog.controul.com/2009/04/how-slow-is-static-access-in-as3avm2-ex...

Otherwise an interesting article :-)

Re: AS3 is slow

It is slow compared to Java, when they should be comparable when statically typed. Obviously the Java machine has vastly more effort, but none the less I'm not impressed with AS3 overall.

Also, static typing is a different kettle of fish from static members. Blame C/C++ for overloading the word static with too many different meanings.

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.