Event Handler Style Showdown

There has been some talk on Twitter recently about the best way to write an event handler. This is all in good fun of course as there is no right way to do any kind of code. Flashers come from all walks of life. Some are from the design world and some from serious development backgrounds. Below are some of the suggested ways. What do you think?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private function kermanStyle(evt:Event):void {
    // this is nice but I don't like evt for some
    // reason. Also it is much more readable and
    // clean to put the opening { on a new line.
}
       
private function sacksStyle(event:Event):void
{
    // Steven rightly puts the opening { on a new
    // line but uses the word event for his event
    // object. You should never use a lowercase
    // version of an existing class for an instance.
}
       
private function brimelowStyle(e:Event):void
{
    // Yeah baby that's what I'm talking about!
    // Using e is short, succinct, and most of all
    // it is the sign of high intelligence.
}

Commentary

  1. You guys are all wrong.

    private function ogStyle( event:Event ):void
    {
    // Hell yea, this is where its at
    // Using event makes it read smooth like common English
    // it is the sign of supreme intelligence.
    }

  2. Damn I’m wrong too, I forgot the underscore.

    private function _ogStyle( event:Event ):void
    {
    // Hell yea, this is where its at
    // Using event makes it read smooth like common English
    // it is the sign of supreme intelligence.
    // Now its right, and you’re all wrong!
    }

  3. I’m a cross between kermanStyle and brimelowStyle:

    private function labrecqueStyle(e:Event):void {
    // Keep { on the first line – habit, probably
    // Do prefer keeping the “e” nice and short
    }

  4. Tahir Ahmed says:

    Haha! brimelow wins for me. I have the same but with a lil more indentation !!

  5. Rhuno says:

    I use evt, but I do put the opening brace on a new line. I like it better when the braces line up nicely.

  6. Pedram says:

    I’m in brimelowStyle!

  7. I’m going to have to combine for the fincanonStyle if I may:

    private function fincanonStyle(e:Event):void {
    // I also prefer e instead of evt or event
    // but I don’t like my { on its own line.
    }

  8. Lee Brimelow says:

    @Omar please don’t put spaces between the parenthesis and your arguments. Please just don’t do it man.

  9. Micah says:

    I like the brimelow style, but i modifiy it for the types of events, slightly more descriptive, but still small amount of chars

    i.e

    private function micahStyle(me:MouseEvent):void
    {

    }

    private function micahStyle(pe:ProgressEvent):void
    {

    }

  10. Oops… guess I can’t claim that one since Labrecque beat me to it while I was typing. ;)

  11. Tahir Ahmed says:

    Whoops !! forgot to post mine ..

    private function (bang a few tabs here)brimelowStyle (and some more)((a space here)e:Event (and there)):void
    {

    }

  12. iBrent says:

    Dude Lee,

    You’re flip-flopping on the issue. I remember when you exclusively used event:Event. What’s changed man? Who’s gotten to you? Come back to your roots bro!

    ;-P

    iBrent

  13. jaime3e says:

    private function handleSomething(e:Event=null){

    }

    what if i skip the :void? does it make any difference?

  14. Lee Brimelow says:

    @iBrent did I really? Send me a link if you find one. Actually tools like SourceMate generate them with ‘event’ so maybe I just never changed them.

  15. Brian Sexton says:

    I do prefer for curly braces to line up and I tend to name my event parameters “e” even though that is not a very descriptive name. However, I disagree with your assertion that “You should never use a lowercase version of an existing class for an instance.” When I have only one instance of something within a scope, a lower-cased version of the class name seems perfectly appropriate; it is descriptive, its purpose and association are clear, and contrary to the most likely argument, it is easy to distinguish from the class name—especially when referenced explicitly through an object (e.g., this.textField or scoreBox.textField). Good syntax coloring and type icons can make the difference even clearer.

  16. Lee Brimelow says:

    @Brian yeah I probably have done that before too, especially with custom classes :)

  17. PrivateSchmivate says:

    You guys are all wrong. The correct way is:
    protected function awesomeStyle(e:Event) {
    // do something
    }

    (speaking as someone who’s had to spend way too much time reimplementing or copy-pasting code due to the lack of override-ability. Also someone else’s argument to the same point: http://www.parashift.com/c++-faq-lite/basics-of-inheritance.html#faq-19.8)

  18. zedia.net says:

    Programming languages tend to be more and more human readable so I think we should adjust our coding habits in that sense too (someday we will code just by writing English).

    Also Adobe, in their coding conventions advise on using event and not e or evt. http://opensource.adobe.com/wiki/display/flexsdk/Coding+Conventions#CodingConventions-Eventhandlernames

    For all those reasons I stick with Sacks

  19. JesterXL says:

    Adobe coding standards state to use event:

    http://opensource.adobe.com/wiki/display/flexsdk/Coding+Conventions

    Flash Builder 4 code generation automatically follows that standard.

    #sacksStyleFTW

  20. simon says:

    private function simonStyle(e:Event):void
    {
    // that’s how i do’s it Larry
    // the most aesthetically pleasing imo
    }

  21. Will Costa says:

    I Try to follow the coding conventions http://opensource.adobe.com/wiki/display/flexsdk/Coding+Conventions

    So i use event instead of just e or everything else, but i just can’t put the curly braces in the next line, it’s an old habit…

  22. Lee Brimelow says:

    @Jester yeah for some reason they didn’t ask me to write the coding conventions :)

  23. Ain Tohvri says:

    Most of you guys are well wrong. The correct way to do it is event:Event as by the Adobe’s very own coding convention:

    http://opensource.adobe.com/wiki/display/flexsdk/Coding+Conventions#CodingConventions-Eventhandlernames

  24. Lee Brimelow says:

    @Ain they also want you to use ‘handler’ in the name of the function. Adobe is wrong in this case :)

  25. russdogg says:

    I’m from the LeeBrimelow School of Actionscripting, so I’ve always put my open bracket on a new line :) The other way just looks wrong to me.

  26. Let’s face it, you’re all wrong.

    private function onRalphStyle(event:Event):void
    {
    //This is the way to do this. Oldschool ‘on’ before any event handler to signify handling of an event ;-)
    }

  27. Steven Sacks says:

    “You should never use a lowercase version of an existing class for an instance” – Lee Brimelow

    The only thing you should never do is use the word “never”.

    I use lowercase versions of existing classes ALL THE TIME. There’s nothing wrong with it.

    var shape:Shape = new Shape();

    var scrollbar:Scrollbar = new Scrollbar();

    var label:Label = new Label();

    “Confucius say, man who codes on timeline has no class.”

  28. the sacksStyle rocks!! and use “event” as the name of the var is part of the recomendations of the Coding Conventions ;) http://opensource.adobe.com/wiki/display/flexsdk/Coding+Conventions#CodingConventions-Argumentnames

  29. Rob Fox says:

    third is win!

  30. Steven Sacks says:

    @Ralph You’re goddamn right, Ralph. People who don’t use onNounVerb() are writing event handlers wrong.

    I hate seeing

    function clickHandler()
    function buttonClick()

    BLECH!

    This is way better:

    onButtonClick
    onScrollUp
    onRalphRules
    onStevenAgrees

  31. Lee Brimelow says:

    How about this you verbose mofos:

    private function verboseStyle(thisIsMyEventObject:Event):void
    {

    }

  32. polyGeek says:

    private function polyGeekStyle( e:Event ):void {
    // place spaces before/after the param:type
    // Anyone who uses “event” should stop calling it “email” and instead use “electronic Mail” :)
    // I use the only coding conventions that matter – mine.

    // CODE CUDDLING FTW!
    }

  33. @admin sometimes i don’t use it, but i makes things easier to read when there’s more arguments. I can live with this though:

    private function _ogStyle(event:Event):void
    {
    }

  34. private function _onClick($evt:Event):void {
    // underscore for private functions
    // dollar signs for all arguments, and ‘evt’ over ‘e’ because ‘e’ could be
    // slightly ambiguous (is it an event? an error?)
    }

    Also I cuddled the brackets, because that’s just the kind of guy I am.

  35. Lee Brimelow says:

    This Dirty Harry lines applies well here:

    “Opinions are like assholes, everybody has one.”

  36. Lee Brimelow says:

    @charlie wow that is an eyeful. You would like Obj-C :)

  37. flashopen says:

    Just noticed that I use Phillip’s way… exactly!
    Maybe it is a sign of high influence!

  38. Troy Gilbert says:

    Definitely with @Ralph on this one (or modified Sacks style, whatever). Using the lowercase version of a class name for an instance is *classic* programming technique for throwaway and/or local vars.

  39. Lee Brimelow says:

    Just to add fuel to the fire. If your conditionals only have one line, loses the {} and just indent.

    if(lee.rules)
        trace(“Well duh”);
    else
        // nothing needed here

  40. Emel says:

    This is how I roll, powered all accross my code by FDT CMD + F syntax formatting:

    private function handleChangeEvent( e:Event ):void{
    // uhlalalaaaaa….
    }

  41. Kevin Newman says:

    I like it obfuscated style..

    dynamic class Foo {}
    var br:Foo = new Foo;
    br._sctdElyts = function(…$rst) {
    try {
    var e:Event=$rst[0] as Event;
    trace(e['eventProp']);
    }
    catch(r:Error) {
    // Silently suppress.
    }}

    ..with lots of uneeded overhead, and conventions from other languages. :-)

  42. This is so funny. Here are some of my reasons for doing it the way I do. Mind you, I teach AS3 quite a lot and that is part of my reasoning.

    First off, and extra line for the first curly brace just takes up vertical space which gets limited on projectors, in book printing, and really on any one’s widescreen monitor. Ultimately I don’t care what people do as long as they’re consistent.

    Second, evt (short for event) is better for me because when teaching I can get into actually building stuff WITHOUT EXPLAINING THAT PARAM! Keep in mind you really can’t do anything interesting without event listeners. I always have to spend a fair bit of time explaining addEventListener and the corresponding “destination function”. To have to add to that a complete explanation of the event/evt parameter i is simply a distraction I don’t want to get into at the beginning of teaching. I’d rather have students start building. So, regardless of whether I call it “evt” or “event” I certainly don’t give it a full description until later. So, in fact, using “evt” which is slightly more cryptic is good because I don’t want the students thinking too much about this detail right at the start.

    On top of this, I’ll bet you’ll love this: when I teach, I begin without event typing the evt parameter (or the return). I just say, “for now, just put evt in there for any function that serves as a destination for a listener”. Naturally, I’d like to explain everything but, remember, you could spend hours and hours on details that just delay the students from beginning to build stuff (and have fun… then get motivate to go on).

    Consider too that if I put “event” in there it turns blue (due to the fact I’m burdened by teaching AS inside of the Flash IDE). Why does that turn blue? I don’t want students to think it’s a reserved word.

    Finally, my personal code style is to follow this convention:
    the parameter is always evt but, if inside that function I create a new event instance (most often a custom event of my own) I store it in a local variable and name that variable event. Like:
    function handleClick( evt:MouseEvent ):void{
    var event:MyEvent = new MyEvent( MyEvent.CONSTANT, true );
    event.myProp = “value”
    dispatchEvent ( event );
    }
    Hope you like the extra spaces.

    By the way, why would you all want an extra line for the first curly brace but not extra spaces next to parens? Makes it way easier to read I think.

  43. P.S. I don’t like “e” because I think of natural logs.

  44. private function brimelowStyle (e:Event) : void
    {
    // find that extra space helps for reading
    // I also enforce my students adopt my style :-P
    }

  45. Jamie says:

    I am completely with @charlie. I used to do exactly as Lee did (except also with $evt for argument) but our way is completely readable — you can immediately tell what the argument is and what kind of argument.

  46. JohnO says:

    You’re all wrong. Its about job security. “One line” that mofo and keep everything cryptic.

    private function $a( …rest ):void { // p.i.t.a for everyone; // add in multiple lines; // client can’t outsource or nothing; }

    Ok.. kidding.. I don’t think it matters at all as long as you are consistent. For the record, i follow Steven Sacks style with event:Event, but formatting is all done by FlexFormatter. However, when I teach, I tend to use evt:Event because saying “event of type Event” over and over to new students tends to cause their eyes to glass over.

  47. Barrett Paul aka @waveposition says:

    Seeing as I learned AS from Phillip in school about 10 years ago now. I’d have to agree with his approach. (can you retrofit my grade in that class with some extra credit now!) and more importantly it just makes sense. don’t drop the brace to a second line – byte hogs – damn – but having been glued to the tube at gotoandlearn.com i gotta give Lee props!! Mad Props!!

    e: is slightly more cryptic than evt: though both are pretty self explanatory. and I’ve always understood that reserved words should be left alone.
    Blammo!

  48. @Steven Sacks says
    “I use lowercase versions of existing classes ALL THE TIME. There’s nothing wrong with it.”

    That’s fine except two things:
    1. what do you do when you need another instance?
    2. how do you explain it to a student vs. using “my” like myClassName

  49. Lee Brimelow says:

    To keep things even shorter, create an alias for addEventListener:

    var eh:Function = this.addEventListener;
    eh(Event.ENTER_FRAME, l);

  50. Devin Reimer says:

    kermanStyle + sacksStyle = reimerstyle

    private function reimerStyle(evt:Event):void
    {
    // { on a new line (brackets should line up)
    // agree – should never use a lowercase
    // version of an existing class for an instance. ie: event
    // also should never having a single letter variable,
    // outside of a for loop counter
    // evt – says it is an event and it’s short, best of all worlds :)
    }

  51. Devin Reimer says:

    Like to change one thing about my last comment, ‘should never use a lowercase version of an existing class for an instance.’ The word ‘never’ in there I think is too strong as it sometimes does make sense. It would be better to say, ‘you should try to avoid using a lowercase version of an existing class for an instance’

  52. jack says:

    sacksStyle++

  53. Abraham says:

    Haha! :P
    Ralph’s style is the one I use.

    I mean look at it:

    private function onRalphStyle(event:Event):void
    {
    //This is the way to do this. Oldschool ‘on’ before any event handler to signify handling of an event
    }

    the “on” at the beginning -> you can hear it say “Hi! I’m an event”
    the event param -> makes things super clear!, c’mon guys, “event” is not a long word!
    the braces on diffrent lines -> readableCode++ (at least for me)

    Anyway.. looks like we have different perspectives on what makes code more readable.. or “right” :P

  54. Well, I have to this rout dudes:

    protected function onBrimelow (p_e:Event) : void
    {
    // definitely have to put the ‘on’ and
    //bringing in the old Peldi style with the ‘p_” to
    //note when your using the original parameter.
    //AND im using protected so that people can always
    //extend my madness.
    }

  55. Ange says:

    @JohnO – you mean refuctoring http://www.waterfall2006.com/gorman.html

    I hate conditionals without braces, one of my colleagues does this all on one line, brrr!

    I’m a

    private function handleWhatever(event:WhateverEvent):void {
    }

    kind of gal myself,

    with a

    event.currentTarget.removeEventHandler(event.type, arguments.callee)

    if appropriate too

    (forgive any syntax errors, is Friday night, half a bottle of wine down post IT Crowd)

  56. Rezmason says:

    Some of you think “e” is a perfectly valid variable name. WRONG.

    Never, ever, EVER use single-character variables in a project. If you’re jotting down a quick script, it’s fine. But who would want to do a search for the variable “i” in this mess, for instance?

    for (var i:int = 0; i < initialList.length; i++) {
    if (i == init && isDirty) isDirty = !isDirty;
    var indices:Vector = initialList[i].indices;
    indicies[i] = initialList.indexOf(indices);
    }

    Use AT LEAST three characters (like “evt”) when you’re writing code, if not for your own benefit than for the rest of us. “evt” is very searchable for a three-letter name. I also tend to replace “i”, “j” and “k” with “ike”, “jen” and “kim” for the same reason.

  57. Jon Williams says:

    of the many horrors with varied coding styles out there, I think I can manage a little search-and-replace action if I don’t like how the other guy did it. Choosing e, evt, event, myMoreDescriptiveEvent, whatever…

    I think it’s only really worth having an opinion about if you have to resort to regular-expressions (or worse) to “fix” it.

  58. Alan Shaw says:

    If I’m clear about what a function does, then I try to name it accordingly, whether it takes an event as parameter or not. If I can’t describe it better, I do call it onSomething() and feel it’s not complete. I can see what event it’s handling from its signature and the mapListener() call. DRY. I also prefer keeping my event types (the magic strings) pretty much one-to-one with the Event classes. It’s really silly to have twenty event types grouped into one class just because they are all dispatched by a particular view component or mediator or proxy. The framework is not too concerned with where an event came from, and if you care about that it’s available as a property of the event.

    Do you name all your Event classes with the word “Event” at the end? Does that add anything? As with functions, I try to name Event classes in a way that helps me remember what they’re for: “NavigateToSettingsPageRequest,” not “SettingsPageEvent.” The latter tells me nothing.

    And no, I’m not worried about the proliferation of event classes weighing down my app. Not in my context.

  59. Si Robertson says:

    Personally I always do this …

    function onSomeThing( event:Event ):void {
    //
    }

    … it’s nice and compact, readable, and using “on” makes it obvious the function is an event listener (as opposed to a generic function that requires an Event as a parameter).

    That style has never caused me or anyone else I know any problems within the code or with refactoring etc :-)

  60. Isaac says:

    I hate having the opening bracket on a new line. It’s a share waste of vertical space. Screens are extending horizontally, why should I waste vertical space?

    Sorry I really don’t like scrolling so I prefer it on the same line as the function.

  61. e is only easier to type, not to read.
    good code is readable and verbose.

    i try to write for future readers, including the autocomplete engine.

    i like the adobe standards.

    object_eventNameHandler(event:EventClass){

    the Handler is a little horsey, although it does jump right off the page when you scan the source code.
    the leading object_ is nice because it autocompletes, so why not include it, it comes in handy when you have multiple objects responding to the same eventName. also, works nicely with FlexFormatter’s auto-alphabetizer, i can always find the block of event handlers related to a given object.

    more than anything its nice to just go with adobe standards so that personal style choices are not a factor in team coding and everything fits the same template. this way if you dont agree with that style, you only have to get over it once. rather than a mix of different styles on a team.

    where your brackets land is probably has the least effect on readability than any of these considerations.

  62. vamapaull says:

    Until a few weeks ago I had a combination between kermanStyle and brimelowStyle:
    private function oldVamapaullStyle(e:Event):void{
    // my old style
    }

    Recently I’ve changed to brimelowStyle because a friend of mine pushed me to sacksStyle and I believe I was just to lazy to write event:Event and I used e:Event instead :lol:

  63. Isaac says:

    Better off:

    this.addEventListener(MouseEvent.CLICK, function():void { //Make everything one line; :) });

  64. Jason Merrill says:

    Sacks style all the way. There is no need to sacrifice clarity for brevity in this case. Sorry man- make it readable! But I do agree with dropping brackets to the next line.

  65. Fedlarm says:

    SacksStyle +1.
    Here’s why. Since we got a nice thing called code completion, i cannot see a reason not to use it, and therefore, the name length doesnt really matter that much. A full length name on your variables is always readable, and more enjoyable to read. Just like a good book is more enjoyable to read more than a SMS. Fine if you are making banners all day, write ‘e’, the sms way. But for us who like to make stuff easy and enjoyable to read, makes full describing names on functions, variables, etc.

  66. Richard Lord says:

    Euler got there first, in the 18th century, when he chose e as the symbol for the natural logarithm. To use it for Events too is confusing. Next thing we know, someone will suggest using it for Errors as well and chaos will ensue, culminating in the end of civilisation.

  67. Fedlarm says:

    @Isaac, the inline function is not a good practice. You won’t be able to remove that listener again. It also puts more code together and makes your code messy a lot faster. You won’t be able to group your methods, and if you do start to reorganize your inline methods, the’re is a fairly big change you’ll start to fuck up some code.

  68. Andreas Renberg says:

    My style is a bit more like “Brimelows”, but I’m a bit more descriptive in the variable name of the event parameter.

    private function onEnterFrame(ev:Event):void
    { //Newline, baby!
    // Content here
    }

    But for specific events (specifically MouseEvent and KeyboardEvent, I name the parameter differently for clarification.

    private function onClick(mev:MouseEvent):void
    private function onKeyDown(kev:KeyboardEvent):void

  69. My style is a bit more like “Brimelows”, but I’m a bit more descriptive in the variable name of the event parameter.

    private function onEnterFrame(ev:Event):void
    { //Newline, baby!
    // Content here
    }

    But for specific events (specifically MouseEvent and KeyboardEvent, I name the parameter differently for clarification.

    private function onClick(mev:MouseEvent):void
    private function onKeyDown(kev:KeyboardEvent):void

  70. Marc Hughes says:

    brimelowStyle for me. But I’d call it Marc style :)

  71. Orlando says:

    “Also Adobe, in their coding conventions advise on using event and not e or evt. http://opensource.adobe.com/wiki/display/flexsdk/Coding+Conventions#CodingConventions-Eventhandlernames

    Adobe uses ‘event’, so should everyone else.

  72. Kirk Elliott says:

    @og i think underscores are for arrays, not functions, but to each his/her own.

  73. jvcleave says:

    I find that using e helps the target in e.target stick out a bit better than event.target. Also typing e:E(Ctrl+Space) has a nice flow to it.

    In writing the coding conventions for our company and after years of onMouseClick style we went to a mouseClickHandler in an effort to be closer to the Adobe convention. I still am jealous when I see others use onMouseClick.

  74. Delfi says:

    I do agree with Kerman: ‘e’ is for natural logarithms.

  75. who are these kerman and sacks guys? e:Event FTW

  76. Evan Warner says:

    There are a few variables in programming that have (or are gaining) their own identities. i is a loop counter, j is a subloop counter, n is a total or max value. To me, e has reached that point in the world of Actionscript. None of these are descriptive (though i comes from “iteration” and n comes from its use in mathematics), but we comfortably use them because we’re familiar with them from prolonged use.

    What they all have in common, which to me makes them appropriate, is that they’re all local variables. They’re only used in the context of the code block they’re declared in, so understanding their meaning is very simple. It’s a habit born from laziness, yes, but I don’t see anything particularly wrong with it.

    I use e, but have no problem with anyone using evt or event or heyCheckOutThisAwesomeEventObject. Ok maybe that last one…

  77. John says:

    You guys are all wrong.

    // Some ridiculously long comment that will only be understood by me and my brother (who isn’t a programmer).
    // Where’s the method? We’re getting to it, don’t be so impatient.
    // A funny thing happened to me on the way to work today.
    // How about that iPhone4?
    // We’re going to create a class just for this function. Why?? Shut up!!
    /* omit the modifier, privacy is dead */function somethingThatRelatesToAnEventFromAnotherProjectSoItMakesNoSenseAndWastes
    3HoursOfYourDayAndMakesYouWonderWhyYouChoseToBeADeveloperInTheFirst
    Place(yoMomma:Event):void
    {
    // Always start a new line.
    }

  78. Allan Bishop says:

    brimelowStyle of course. It is the most visually pleasing, efficient way. I mean, in simple for loops we all use ‘i’ right? ;-)

    Not a fan of cuddled braces. To me it is like someone wearing their glasses crooked – It gets the job done but I would think twice before asking them for street directions :P

    Oh, and onNounVerb is the way to go for the event listener :D

  79. Jonathan says:

    the best way…the generated way :)

    protected function treeData_resultHandler(event:ResultEvent):void
    {
    //just awesome
    }

  80. Jonathan says:

    the best way…the generated way :)

    protected function treeData_resultHandler(event:ResultEvent):void
    {
    // just awesome :)
    }

  81. Steven Sacks says:

    I think that basing your coding style on how you teach students is an indefensible position to take when discussing best coding practices. At first, you teach students to code on the timeline without classes, too, so does that mean that’s how you should always code? Of course not.

    I disagree with teaching students bad habits first and then correcting them later. I think that’s a lazy teaching methodology which is counterproductive. People remember how they first learn something. If you don’t teach good habits to begin with, they’re going to have a tough time later on.

    And here we get to the crux of the issue. You have no reason to care. Once they’re out of your classroom you never have to deal with them again. You don’t have to inherit their code, you don’t have to work with the coders who have to inherit their code. You never see them again. You’re teaching the next batch of fledgling developers bad habits because it’s “easier” on you, the teacher.

    On another note, putting underscores before private function names is retarded. You’re already assigning the function to the private namespace. No further demarkation is required. Further, the only private variables that need underscores before their names are those with getters/setters.

    $prop is php garbage, where you have no choice.

    /opinionatedrant

    :)

  82. private function McLaughlinStyle($evt:Event):void
    {
    // Styles
    // For
    // Miles
    };

  83. @Steven Sacks

    I think the point about teaching is not as totally wacky as some of your other points–but I don’t teach in a way that’s lazy but with just one priority: teaching. You have to make sacrifices or you can spend all 30 hours of class time on how to configure their code editor and why import is necessary and why typing is better, using constants etc. etc. When, in the end, you may not teach anyone to jump in and have fun. You didn’t start programming the way you do now and, at least for me, even after 15 years of solving problems with code–the stuff I built 6 months ago is borderline embarrassing.

    This bit about me not having to inherit their code etc. Sheesh. I don’t want to inherit my code from 1 year ago let alone anyone’s. But, if it’s consistent why would I care? Inheriting a timeline with stop() on every frame is painful, but I’m sure (as any good programmer could) I could learn to even look past such whackyness as the dollar sign in var names.

    Having said all this, I also think it’s a mistake to treat students with kit gloves and protect them from the hard work. Recently I’ve introduced class files very early and it’s turned out very well–even helps students who may never code beyond the timeline. Keep in mind, some people aren’t as smart or programmer oriented as you–so it might take hours of lecture and practice to get something you think is simple.

    Sure, I shouldn’t teach stuff I know is bad. Here’s a great example:
    I start with listening for “click” (not MouseEvent.CLICK). Then I get into the diff later. Some still have trouble. [[SIDE NOTE: I can't stand that Flash IDE makes you import some classes but not all--argh... this makes class files harder when you do get to it]]

    Anyway, I know you’re being extreme to try to make a point. But, do you teach? If not, try it. I know you are a great communicator when I’ve seen you present. But, no matter how good you are at teaching you can always get better.

    Finally, I’ll repeat the bit about how any good programmer can look past any style stuff just as they can learn and adapt to other (seemingly wacky) languages.

  84. Aaron Hardy says:

    Sacks++. Holding…back…fisticuffs…

  85. Jay Jagpal says:

    Sorry guys, I have to interject. Being a Flex/Flash teacher I advocate this style.

    submitButton.addEventListener(MouseEvent.CLICK, submitButtonMouseClickEventHandler);

    private function submitButtonMouseClickEventHandler(ev:Event):void
    {
    //…
    }

    Reason being you can look at this function, never and understand its use without ever finding its handler.
    [ObjectName][Event]['EventHandler']

    I use ‘EventHandler’ as someday you may want a handler that doesn’t handle an event. this would be ‘SomethingHandler’

    The event type may differ from a ‘mouse click’ to a ‘pen click’ one day and I wouldn’t want my syntax to break.

    I use ‘ev’ as I may want to create an event to send in the same method:

    var event:Event = new Event(); //…etc…

    Never use ‘pe’, ‘me’ or any other rubbish particular for each event as then you’d have to read a function to completely understand whats going on. that not easy in big project.

    Simple, Clean – CORRECT! [Grrr]

  86. Jay Jagpal says:

    I’d like to add I use ‘event’ for java, ‘e’ for C and javascript. ‘ev’ for actioinscript…

    just becuase their all OOP languages – doesn’t mean they all follow the same conventions.

  87. I couldn’t resist!

    protected function onEventName(p_evt:Event):void
    {
    //code
    }

    so for example addEventListener(Event.CLOSE, onClose)

  88. Dave Gamez says:

    I’m used to the “e” style for a while now :)

    private function onEnterFrame_handler(e:Event):void
    {
    /*/
    I prefer that the method name does the explaining of what it does, and have only the “e” .
    stop();
    hammerTime();
    //*/
    }

  89. Ed Moore says:

    I use brimelow style. One: because it looks nicer. And two: FlashDevelop’s code completion tool does it that way. Yes i’m lazy. But hey it speeds up development time.

  90. Tahir Ahmed says:

    Hmm, so thats why developers hate working on someone else’ code.

  91. private function myOpinion(everett:Event):void
    {
    // some funny comments, like this discussion
    // Silly smilie (“,) why not?
    }

  92. Luke says:

    protected function onLukeStyle(e:Event):void
    {
    }

    I always prefix my handers with ‘on’ which is nice and short. Some people prefer to add ‘handler’ which I personally find a bit to long. Also, I use protected instead of private because I’d like to be able to override handlers in subclasses. I actually very rarely use private for that same reason.

  93. sakri says:

    Guys who don’t cuddle their braces just happen to really enjoy scrolling. I don’t understand it, but then again, I have trouble understanding how a blog post like this gets 800 replies :D

  94. Steven Sacks says:

    @phillip All good points. And yes, I was being extreme to make a point. Style-wise, I’ve been consistent for at least 3 years now, and some of my naming conventions I’ve used since my early days with Flash MX.

    I’ve tried many styles over the years. I generally do not rule out a style until I’ve tried it for at least 30 days to see if I like it or not.

    I’ve tried p_foo parameter names. Those are a gross remnant of procedural coding. The only argument for them is that they stand out from local and instance variables within your functions, but if your function is long enough that you can’t see your function declaration anymore, it’s generally a sign that it’s time to refactor.

    I’ve tried $foo parameter names. At first to avoid having to use this.foo when setting instance variables from passed in parameters (I don’t like the style of using this. throughout a class – it’s obvious when you set variables that they belong to “this” – redundancy is wasteful and it’s not unclear if you don’t include this). However, the $foo style resulted in ugly code hints and tooltips when you use good code editors, so I dropped the $ and lived with the limited this references when required.

    I used to hate uncuddled braces. I gave them a month long trial. Now, I can’t imagine going back.

    I like single line if statements when the action is only one line, but I don’t like indenting without braces.

    if (true) doSomething();
    else doSomethingElse();

    With rare exceptions, I do not like closures (and I’m not alone). They make code less readable, they cause issues with code hints and lexical parsing, and in AS3, it’s generally a bad idea to use anonymous anything lest you can’t clean it up.

    As Ralph mentioned, naming event handlers onSomething makes them very easy to see in your code. Much more easy than putting the word “handler” at the end of your function name. That means you have to read all the way to the very end of the function name to know what it is OR read from the end first. Both of those things cause a state break.

    A few years ago, a C programmer friend of mine recommended onNounVerb as opposed to onVerbNoun. At first it felt a little odd for some things, but it actually makes reading code easier, as English often follows that pattern.

    onClickButton (verb noun)
    vs
    onButtonClick (noun verb)

    That’s an easy one to argue could go either way, but what about this:

    onReadyModel
    vs
    onModelReady

    The obvious winner is the latter (noun verb). So, if you’re going to write consistent code, you should always use onNounVerb and not mix it with onVerbNoun.

    This might be up to personal taste, but, again, for years I was a verb noun guy for some things and noun verb for others, switched to noun verb for everything for a month, and haven’t looked back.

  95. Steven Sacks says:

    I realize that the second example is onNounAdjective not onNounVerb. Either way, the noun comes first and the action or state comes second.

  96. Avi Tzurel says:

    I usually use e and not event, I am used to it.
    although since I installed SourceMate for flash builder 4, the event handler generated uses event as the variable name, I got used to that as well.

  97. I’m on this:

    private function nameExplainingTheFunction(e:Event):void {
    //
    }

    or

    private function nameExplainingTheFunction(m:MouseEvent):void {
    //
    }

  98. Danel Kirch says:

    kermanStyle and brimelowStyle is the shit!

    but i do it with a twist, first letter of the event

    private function funcFunc(m:MouseEvent):void{ }
    private function funcFunc(p:ProgressEvent):void{ }
    private function funcFunc(e:Event):void{ }

    Anyways there are no wrong ways to code! To state that, can be compared that someone is thinking wrong in their mind. There is no “wrong” when you get no error, but there is ways to think differently.

    Rock on!

  99. Paul Neave says:

    It doesn’t matter which style you chose. The most important thing is to be consistent throughout your code. Chose a style and stick to it. I prefer the Sacks style, but that’s just my preference. All my code is written that way, and if you work in a team, everyone should agree on using one style and stick to it also.

  100. Greg says:

    I’m also in brimelow style, except for the default assignment to null

    private function myHandler( e:Event = null ):void
    {
    // i like to add the = null because I sometimes re-use event handlers
    // in non-event contexts..
    }

  101. Si Robertson says:

    It’s funny to see that most of the people replying here think that *their* way of coding event handlers is the *correct* way to code event handlers :-)

    The thing is, there isn’t a correct way, there’s an incorrect way (i.e the code doesn’t work) but everything else is valid even if it doesn’t conform to someone’s expectation or to an idealistic standardization.

  102. I use the following:

    private function onMouseClicked(event:MouseEvent):void {
    moveCharacter();
    }

    private function moveCharacter():void {
    }

    Doing this seperates out your handling the event and preforming your action. This means you could switch between using eventdispatching, using PureMVC notifications (yuck!!!!) or even using signals etc.

  103. FlashJockey says:

    I learned AS3 from Lee’s tutorials and i like his style, so i’ll just keep using it I guess :D

  104. Faavtro says:

    Brimelow style for the win! ;)

  105. Being usually quite limited in scope, I really don’t think the name of the event instance argument matters that much as long AS it is consistent. I prefer “e”. What matters more to me is the name of the function. I tend to get frustrated when other devs denote an event handler by simply appending the word “handler” to the end of the name. The reason being that whatever comes before that flag is usually what was at the top of the head of the previous dev at the time of writing, making it harder for me to guess. I always start my event listeners with the word “on”, so that code hinting easily presents me with a list of event handlers to choose from. Also, menuItemClickHandler is harder to read, write and remember, whereas onMenuItemClick just works. It’s easier to remember that you’re looking for an event handler than remembering what exact object dispatches it.

  106. seamonkey says:

    I totally agree!
    brimelowStyle is sweetest ;-)

  107. Yeah. I’m using brimelowStyle to =)

  108. LB says:

    Obviously these differences of styles are impossible to resolve. But I’m compelled to announce here that I find the line break before the opening brace to be so appalling that it actually makes my temples throb.

    function foo():void
    {
    // This is more than wrong – it is an abomination.
    // I will never, never conceded the contrary
    }

  109. steve says:

    Eeeeert! You are all wrong! Thanks for playing! The answer is…

    function objectWithTheEvent_onEventType(oEvent:EventObject):void{
    // You should start with the name of the object associated with the
    // event, an underscore and the event type. The item in the
    // parameter is an object, hence the leading “o”. Always end with
    // void. I like my curlybraces on the same line as the function.
    // Booyeah!
    }

  110. steve says:

    That is how it has been done in the microsoft world for many years. prefacing the event with the object firing the event makes sense unless you have a handler handling similar events from a number of object instances… inwhich case I would preface with an object type.

  111. rob says:

    i always use e for the event. in the scope of the method, it’s pretty self explanatory. i can’t remember when i started using handle but i like it. i like to start my methods out with verbs, buildThis, doThat.

    private function handleEvent(e:Event):void
    {
    //amidoinitrite?
    }

  112. aristophrenia says:

    Signal.dispatch();

    Get with the program…..

    signal.add()……

    Events -………………pffffffffffffffffffffffffttttttttttttttttt!!!

  113. I’m perfectly on brimelow style.

    function flashGuy(e:Event):void
    {
    trace(“This is how we roll”)
    }

  114. Almog Koren says:

    If you do “e” to make it short after a while you can fine yourself doing all kinds of stuff to make things short and simple you might get some bad habits, I personally hate opening up source files and seeing all kinds things like “e” “funt” and so on.

    I prefer the “event:Event” method.

    By the way lee great design, I am missing an “add you comment” at the top or right after the post I hate having to scroll all the way down.

    Thanks,
    Almog

  115. Khalid Bajwa says:

    I proudly profess that i belong to the brimelow clan. I am glad ateast one other sould thinks putting brackets on a new line is a good idea. God, i was starting to think it was a mortal programming sin not to do it !

  116. Ryan P says:

    e and cuddle

  117. RJ Forbes says:

    evt all the way.

    I use readable shorthand for almost all vars when I can.
    thats right, VARSSSS!!

  118. Matt says:

    Hey cool, I use Brimelow style!
    One character variable names save a lot of time in the long run. Do I want to type someVector.[ike] all the time? No. i. Do I want to keep typing e-v-e-n-t when I could just save 80% of my energy ( :P )? No. And if you’re using a real IDE, you can search for “whole words only”, so that’s not a problem.
    Braces should line up. I don’t care, cuddling sucks.
    I disagree about lowercase class names as variables though… I do it from time to time if I know there’s only going to be one instance of it. timer:Timer is a good example.

  119. Minus says:

    I was drilled using the following

    private function myEvent($event::Event):void
    {

    }

    $ signs , and no single letter variables and such

    as far as that list, sacksStyle is closest to my liking :)

  120. Terrence Tee says:

    The CS5 code generation features also generates event:Event!

  121. According to Flex Coding Convention, “Use event (not e, evt, or eventObj) for the argument of every event handler”

    http://opensource.adobe.com/wiki/display/flexsdk/Coding+Conventions

  122. Jason Dias says:

    I use whatever the IDE output for me, and at this point in time IntelliJ outputs the following:

    private function onTimerComplete( event:TimerEvent ):void
    {
    // IntelliJ IDEA Rules!
    }

    =D Drop braces ftw!

  123. WORMSS says:

    Nope, Sorry, All All Wrong… Its

    private function _onEventName_whoseCalledIt(__e:EventType):void
    {
    // Single _ at front to show its private function of the class, like a few have you have done but…
    // Double __ for the arguments and any variable initialised within the class so show that it is only accessible within this 1 function.
    [Alot of you will hate it, but when you have loads of people writing code left right and centre you know exactly if its a local class or local function variable.
    }

  124. Philip Seyfi says:

    I’m with Sacks…

    event:Event FTW
    onButtonClick FTW
    { FTW

  125. “e” all the way. It’s simple and succinct. And if you’re using the “e” var for anything else in your code you’re likely foolish – unless you’ve for some reason needed Euler’s number and defined it as a constant (inline or static).

    Bah! Simplicity kids!

    Though with auto code generation and good auto-complete (haxe) if you start typing “e” you’re more than likely to get it with “event” as well.

    “evt” is just silly. If you’re going to shorten to obscurity go the whole hog.

  126. private function onEventType(ev:Event):void
    {
    //Function name is always on Event type. ex:onMouseClick
    // I use ev because I don’t like evt for some reason and e is error for me
    //I don’t cuddle the braces. Find it difficult to read.
    }

  127. matt says:

    @Jonathan: I like the dollar sign (eg $evt) but the problem with that is that some editors, for example TextMate, don’t include the “$” in the selection if you double-click the word. eg, if you double-click “evt” it will select “evt”, whereas if you double-click “$evt” it will select “evt” and exclude the “$”. Weird bug/feature, perhaps its only a TextMate thing?

  128. Ktu says:

    private function captureClassEvent ( e:Event ):void {
    // ex: menu – captureMenuItemMouseEvent
    // If I can get one EventType per class in one function I’m happy
    // but, this is not always appropriate
    // same line {}, code editors have indentation guides =]
    switch (e.type) {
    case MouseEvent.CLICK:
    case MouseEvent.MOUSE_DOWN:
    }
    }

  129. TheDarkIn1978 says:

    indenting after the first line is where it’s at! clean and crisp. also, i use “evt” because it doesn’t change color in code hinting

    private function indentMeMofoz(evt:event):void
    {
    //i’m more organized than your mother.
    }

  130. Bo says:

    Wow – that’s a lot of comments to walk through, so I might have missed this being mentioned by some one else … but here is my take:

    e is a mathematical constant – not so great.
    event is lower case of “Event” – not so great either.
    evt can be read as “eventually” abreviated – not ideal.

    But

    ev maintains complete clarity. therefore, we have

    private function bestStyle(ev:Event):void {
    // handle event
    }

    So there – we’re done. Obviously, there is no need to discuss where opening “{” and closing “}” go.

    :-)

  131. TheDarkIn1978 says:

    … pretend the above code has an indented code block

  132. Charlie, I tried out $’s once for parameters, but then I read this:
    http://senocular.com/?entry=441

  133. Tom Murphy says:

    eventTypeHandler(evt:Event):void {}

    Try to always name my handlers by the event that calls it. I still use evt though.

    As a bonus, here’s the textmate snippet I use to automate this:

    addEventListener(${1:MyEvent}.${2/(([a-z])([A-Z]))|([a-zA-Z])/(?1:\U$2_$3\E)(?4:\U$4\E)/g}, ${2:eventType}Handler);

    private function $2Handler(evt:$1):void {}

  134. Marcus Geduld says:

    const ADD_EVENT_LISTENER : String = “addEventListener”;

    function getAddListenerFunction( obj : * ) : Function
    {
    var mightBeFunction : * = obj[ ADD_EVENT_LISTENER ];

    if ( mightBeFunction && mightBeFunction is Function )
    return mightBeFunction as Function;

    return null;
    }

    if ( getAddListenerFunction( this ) )
    getAddListenerFunction( this )( Event.ENTER_FRAME,
    function ( e : Event ) : void { trace( “My head hurts” ); } );

  135. leandroferreira says:

    onSomethingDone( event:Event ):void
    {
    // FTW
    }

    also, never do
    if( something )
    doThis();
    else
    doThat();

    either use curly of, if very simple:
    something ? doThis() : doThat(); // only when something is Boolean;

    and:
    variable = someValueThatCanBeNull || defaultValue;

  136. Pelted says:

    I’m an Objective-C / Cocoa guy who is stuck with AS 3 for a few clients…. So:

    private function somethingDidHappen(event:Event):void {
    // Not a fan of obfuscated 1 character instance names
    // And I can’t stand the open bracket on a new line,
    // it looks like crap.
    }

  137. hristo says:

    Mate, I dont know how I read till the end of this discussion, but Marcus, you rock man, I’ve been laughing for at least 2 minutes

  138. @Matt I have never run into that problem in Eclipse.

    @Chris That’s interesting. I strictly use the dollar sign for function parameters and have never run into any issues.

  139. jellix says:

    private function onButton(me:MouseEvent) {
    // a simple Event is an “e”, a MouseEvent is “me” and so on …
    }

  140. patCRUZ says:

    private function patcruzFunc(evt:MouseEvent):void
    {
    //my stuff
    }

    if(patcruz)
    {
    //do stuff
    }
    else
    {
    //do other stuff
    }

  141. Marcus Geduld says:

    hristo,

    You and I have reached some kind of nerd pinnacle. How many humans on Earth would find that funny?

  142. Steve says:

    Here is a question for everyone:

    I think I see the new line for “{” (braces) getting popular in classes and methods like…

    private function myMethod () : void
    {
    //stuff in here
    }

    … but suddenly they don’t seem to apply the new line brace rule consistently like for existing syntax you will often see …

    private function myMethod () : void
    {
    foreach( monkey in barrel ){
    // notice the brace above without a new line
    // I imagine people will say there is a reason for it
    // but I think they are just not being consistant
    }
    }

    … when it should be more like…

    private function myMethod () : void
    {
    foreach( monkey in barrel )
    {
    // notice the brace above with a new line
    }
    }

    The above make sense as a reasonable alternative to …

    private function myMethod () : void {
    foreach( monkey in barrel ){
    // I think this is fine too and more space saving
    }
    }

  143. Brian says:

    I use $ to represent parameters being passed into a function. so . . .

    private function eventHandler($event:Event):void
    {
    $event. whatever!!!!
    }

    Using a dollar sign before all parameters of a method make it easy to understand scope when using conventions for other variables throughout your code.

  144. Marcus Geduld says:

    Steve, I use a new-line for braces. I find code easier to follow if I can clearly eyeball where braces open and close. I am also consistent about it. ALL my open curlies are on new lines — that goes for for loops, while loops, function blocks, class definitions, etc.

    Having said that, I have a rule (that I seem to be almost alone in following) against nesting blocks within blocks, so the above problem doesn’t really come up.

    My theory (backed up by years of teaching and my own dumb brain) is that humans have a hard time parsing nested things. I suspect it’s because we rarely encounter them in nature. Yes, there are bacteria inside worms inside birds, etc., but that’s not the way we naturally experience the world. We experience it as black boxes interacted with other black boxes. Each black box is complete. As far as we’re concerned, it’s not the top node of a hierarchy.

    (On computers, we have files inside folders inside folders inside folders…. but what real-world filing cabinet works that way?)

    So, for instance, you won’t see this in my code:

    var totalColumns : int = 10;
    var totalRows : int = 5;
    var cellSize : int = 30;
    var gapBetweenRowsAndColumns : Number = 6;

    makeGrid();

    function makeGrid() : void
    {
    var shape : Shape;

    for ( var column : int = 0; column < totalColumns; column++ )
    {
    for ( var row : int = 0; row < totalRows; row++ )
    {
    shape = new Shape();
    shape.graphics.beginFill( 0xFF0000 );
    shape.graphics.drawRect( 0, 0, cellSize, cellSize );
    shape.x = column * ( cellSize + gapBetweenRowsAndColumns );
    shape.y = row * ( cellSize + gapBetweenRowsAndColumns );
    addChild( shape );
    }
    }
    }

    Instead, I write this:

    function makeGrid() : void
    {
    for ( var column : int = 0; column < totalColumns; column++ ) makeRows( column );
    }

    function makeRows( column : int ) : void
    {
    for ( var row : int = 0; row < totalRows; row++ ) makeCell( column, row );
    }

    function makeCell( column : int, row : int ) : void
    {
    var shape = new Shape();
    shape.graphics.beginFill( 0xFF0000 );
    shape.graphics.drawRect( 0, 0, cellSize, cellSize );
    shape.x = column * ( cellSize + gapBetweenRowsAndColumns );
    shape.y = row * ( cellSize + gapBetweenRowsAndColumns );
    addChild( shape );
    }

    I find this much easier to read and MUCH easier to debug.

    I've heard and rejected arguments that you should never follow in if, for or while statement with a single line of code. The argument states that even if you only want to do one thing, you should enclose it within curly braces. Why? Because at some point in the future, you'll want to add more statements. So you might as well have a block ready to go.

    I disagree. When I need to follow and if, for or while with more than one statement, I write a new function.

    So, if I have this:

    if ( x == 100 ) rotation = 15;

    And I'm tempted to write this:

    if ( x == 100 )
    {
    rotation = 15;
    alpha = .5;
    }

    I refactor to this:

    if ( x == 100 ) adjustRotationAndAlpha();

    function adjustRotationAndAlpha() : void
    {
    rotation = 15;
    alpha = .5;
    }

  145. Steve says:

    @Marcus Geduld

    Here is an example I think of what you are talking about and maybe a few reasons to consider the standard that many other people adhere to:

    Because code nesting is based on tab stops and one tab stop grammatically is equal to 5 spaces (anyone? anyone? isn’t that correct?) I am going to use the period “.” character to “tab stop” my example below. Here we go:

    Check out this silly function:

    public function myMethod( inputParam:int = 0 ) : Array
    {
    …..var aBlah:Array = new Array();
    …..var blah:int = inputParam;
    …..for( var ndx:int = 0; ndx < blah; ndx++ )
    …..{
    ……….var newNumber:int = 100;
    ……….newNumber += ndx * blah;
    ……….aBlah.push( newNumber );
    …..}
    …..return aBlah;
    }

    Notice that I got this done in a readable manner with one function (one memory allocation) and six variables (including the return parameter on the function for a total of six more memory allocations). So while this is a ECMA macro scripting language that hides a lot of the resulting instructions that must happen within an operating system, ala pointers, this is fairly efficient.

    Let's look at the same example with a non-nesting function-creating priority:

    public function myMethod( inputParam:int = 0 ) : Array
    {
    var aBlah:Array = new Array();
    var blah:int = inputParam;
    for( var ndx:int = 0; ndx < blah; ndx++ ) aBlah.push(doCalc(ndx,blah));
    return aBlah;
    }

    public function doCalc( thisNdx:int = 0, thisBlah:int = 0) : int
    {
    var newNumber:int = 100;
    newNumber += thisNdx * thisBlah;
    return newNumber;
    }

    This code builds 2 functions (2 background memory references, not one as above) and 8 variables (so 8 memory references) for a total of 10 references. With a more real-world example containing more complicated nesting you will be passing variables multiple times to achieve depth allocating unnecessary memory redundantly (remember reference require memory too).

    Also worthy of note: Brace are instructions. Consider the line…

    for( var ndx:int = 0; ndx < blah; ndx++ ) aBlah.push(doCalc(ndx,blah));

    … and this results in the instructions…

    for( var ndx:int = 0; ndx < blah; ndx++ ){ aBlah.push(doCalc(ndx,blah))};

    but your SWF is two bytes smaller (because of less code theoretically). But to save two bytes, you are sacrificing performance in memory allocation with this overall technique.

    In a world where mobile and web app performance should be improving I would argue that using tab stops and creating functions only for purposes of reuse (do you need to call some large chunk of code multiple times?) or to implement consistency (utility or static functions or public interfaces hiding private class functions) would actually make your code more "readable" by the industry as well as potentially improve the performance of your code.

    Having said that… do what works! But if you want people to check the box "works well with others" next to your name after they inherit your code, I would definitely consider reading up on and adopting standards before reinventing them.

  146. Shawn says:

    Using single character variable names is just plain GHETTO.

    I do it in vary simple spikes, when I am being purposefully lazy, but in production code, never, it’s gross…

    The only exception is counters, since that is an accepted convention in almost all programming languages.

    Oh, and non-cuddled brackets are pretty gross too. You already have a big BLUE word indicating the start of your block, why do you need another line? Total waste of space…

    Handlers should always start with “on”, easier to read, easier to parse your class outline and find all handler by simply entering ‘o’ as the first character.

    In the end, the perfect and 100% correct method is:

    protected function onEvent(event:Event):void {
    ///Ahhh that’s the ticket right there…
    }

  147. Shawn says:

    Oh, and private functions? COME ON. ;)

  148. Steve says:

    @Brian

    I use a few old naming conventions as well. In PHP all variables start with the “$” character but I don’t honestly carry that over into other languages outside of PHP.

    These are the ones I’ve adopted over the years:

    private var _ClassLevelVariableStartsWithUnderScore;

    public function myFunc( thisIsActuallyAFunctionLevelVariable: int )

    var functionLevelVariablesAreSimplyCammelCaseLikeThis: String;

    That is the first level of naming conventions. Next is all about typing!

    var aLittleLetterADenotesThisIsOfTypeArray: Array;
    var bYouGuessedItBoolean: Boolean;
    var sStringOfCourse: String;
    var iAndThisWouldBeInteger: int;
    var nNumberYep: Number;
    var vsStringVectorAsYouWouldImagine: Vector;
    var oThisMeansTheVariableIsTheInstanceOfAnObject;

    In the early days of Flash variables would get some simple style intellisense code hinting if you suffixed your variable name using specific naming conventions like…

    ThisWasATextField_txt
    ThisWasAMovieClip_mc
    ThisWasAButton_bt

    With better intellisense I think it is time to adopt some of the more well accepted industry standards on naming conventions.

    Final note: back in the cobol / pascal days program sizes were crazy optimized, so names were as simple and short as possible. This resulted in crazy cryptic variable names. If you had to read someone elses code you were left to figure out what “sSSNBPC” meant! Because performance matters and disk space is less of an issue, people have been recommending more readable variable names like “strSocialSecurityNumberByPostalCode”. Now that app size in KB matters again due to mobile deployment, I imagine both things have to come into balance.

  149. Mehdi says:

    using e, evt or et instead of event means you do not have enough knowledge of AS3 and afraid that your program will break.

  150. Fishing for comments, I think.
    This is just a matter of taste, nothing more.

  151. Mark says:

    Had to leave my style on here (I don’t think I’ve seen it yet!).

    button.addEventListener( MouseEvent.CLICK, buttonClickListener );

    protected function buttonClickListener( event:MouseEvent ):void
    {
    // that’s the spot!
    }

    It’s protected so it can be overridden in subclasses. The method name starts with the name of the event dispatcher (who), then the event type (why) and then “Listener” (what). If anyone looks at this code it’s really obvious as to the circumstances that would invoke this method.

    Mark

  152. btibia says:

    I am using this one:

    private function btibiaHandler($e:Event):void
    {
    //i’m using $ before any function parameter
    //to see the difference from local(class) variables/const
    //you can read it very easy
    //doesn’t matter the word: e, event, evt
    //everybody use what they like to, i use e because is shorter :)
    }
    :)

  153. Yannick says:

    private function gregoireStyle(e:Event=null):void{//allon1line}

  154. Marcus Geduld says:

    @Steve, I hear you, but it sounds like you’re coding for optimization. I try not to do that. It’s often at odds with readability. I code 100% for readability and then optimize later, as needed.

    I do tend to get a bit binary in my thinking. If you want to argue that you mostly code your first draft for readability but make small concessions to optimization (when readability doesn’t suffer too much), I can see the wisdom. But I kind of need to go into total readability mode to get the job done in a way that’s easy for me to understand and debug. I’d rather do all optimizations in another round.

  155. Marcus Geduld says:

    And I do think your two-function version is significantly easier to read.

  156. Marcus Geduld says:

    “Using single character variable names is just plain GHETTO.

    I do it in vary simple spikes, when I am being purposefully lazy, but in production code, never, it’s gross…”

    In general I agree with this. The rule should be to always make sure it’s s readable and as easy-to-understand as possible. That said, I see no problem with this (let me know if you do):

    function setWidth( w : Number ) : void
    {
    width = w;
    }

    That seems very clear and very readable to me. For more complex functions, I’m definitely on the same page. Basically, don’t use one-letter names if there’s a possibility for confusing or ambiguity. Even more basically, don’t create needless confusion or ambiguity.

    Another exception: if you’re programming a function which uses a well-known mathematical formula — one that’s known by one-letter variables in the math world, it’s sometimes useful to keep the code version the same.

  157. MSFX says:

    BrimelowStylie FTW 8)

    (love the new blog design Lee)

  158. Guilherme Holz says:

    sacksStyle for sure, variables or parameters names have to be readable.

  159. Vemilyus says:

    Brimelow style rockz! Hell yeah, man!

  160. Peter_D says:

    Great tutorial. Every time I learn much more then before :)

  161. Mindshifter says:

    Use event (not e, evt, or eventObj) for the argument of every event handler:
    protected function mouseDownHandler(event:Event):void

  162. Keyston says:

    I use a couple of style

    function component_eventHandler(e:MouseEvent):void // use this mroe in flex applications
    {

    }
    function clickHandler(e:Event):void{ // use this more in flex appliucations

    }

    function onActionRequested(e:Event):void{ // still do this from time to time

    }

    I think i’m going to start using the first 2 more,

  163. Shawn says:

    @Marcus – I don’t hate that, however I’ve gotten in the practice of always setting param names the same as the local class names, and using this. to assign them.

    This is nice because you can give the parameters the name they deserve (nicer for readability, and for code hinting) and you never have to think about what you should name anything, no arbitrary rules about when it’s ‘ok’.

    function setWidth(width:Number):void
    {
    this.width = width;
    }

    To me that is the most readable, and clear.

  164. Shawn says:

    oh damn… that brace should be cuddled!! Nooooooo…

  165. Henrik Hahn says:

    I fully agree with Mr. Skinner:
    http://www.gskinner.com/blog/archives/2008/11/curly_braces_to.html

    Whatever naming convention used for variables must be determined by the employer – and if not – default to common sense and best practice.

    EOD :-)

  166. Lakshman says:

    private function kermanStyle(e:Event):void {
    // this is nice but I don’t like evt for some reason
    // I used to wrtie event, now I try writing e
    // I put the { on the same line as in all the help files of flash 8,
    // cs3 to cs 5, has been a habit
    // And I use a lot of habit
    }

  167. Lakshman says:

    private function kermanStyle(e:Event):void {
    // this is nice but I don’t like evt for some reason
    // I used to wrtie event, now I try writing e
    // I put the { on the same line as in all the help files of flash 8,
    // cs3 to cs 5, has been a habit
    // * And I use a lot of tab indents.
    }

  168. pickgliss says:

    private function __pickglissStyle(event:Event):void
    {
    use “__” for eventHandler
    use “_” for localValue

    }

  169. jloa says:

    Sry, m8s but i can’t agree with this statement => “You should never use a lowercase version of an existing class for an instance.”

    The “sacksStyle” is the right one 4 me. NEVER name yr variables with a single letter! I tear off hands for that.

    event:Event
    // and the code is clean and robust.
    // you’d always know that the ‘event’ var is an Event instance

    Short sample why you should always give logical names:

    Wrong:

    var a:MyMediator:MyMediator = new MyMediator(viewComponent);
    …. (tons of code lines)
    // damn, what did that “a” stand for? O.o

    Right:

    var myMediator:MyMediator = new MyMediator(viewComponent);
    …. (tons of code lines)
    // “myMediator” stands for an instance of MyMediator. Obvious.

  170. Iulian says:

    Regarding “evt:Event”, the reason why this is not appealing, and maybe why you don’t like it, is that it uses 3 different concepts to create one final concept.

    The way the mind works in relation to symbols is through concepts.

    In this case, the 3 different concepts, “e”, “v” and “t” are used to create the final concept “evt”. An the reason why it is not attractive is that it is wasteful, or tiresome.

    In the case of “event:Event”, “event” is a standalone preconceived and undevideable concept.

    The same applies for “e:Event” which is why these last 2 seem more appropriate and less tiresome.

    I personally prefer using “event:Event” because one single letter named variables don’t seem to integrate well with the rest of the function code, they don’t seem to be esthetically pleasing.

    For an index variable, such as in a “for” loop, a one single letter variable is acceptable and looks pleasing but other than that, I rarely prefer naming my variables with a single letter.

    Furthermore, for such a powerful parameter, for it to be so small as an “e” letter, just doesn’t seem right.

    I think that “event” looks esthetically pleasing with the rest of the code and shows the power and importance that the parameter has.

    Although I would very much prefer that the “event” in “event:Event” would not be colored.

  171. Aaron Beall says:

    Wow, so many comments!

    I’ve gone through stages of using each. I started as kermanStyle, but I hate abbreviations, then I saw the Flex coding conventions say to use sacksStyle, so I started using that, then I started using FlashDevelop which uses brimelowStyle in its code completion. brimelowStyle wins!

    Of course I cuddle my braces, so all these styles are wrong. :P

  172. philmill says:

    I use $prop for all method inputs with a mix of Micah’s abbreviations.

    private function onPhilMillEvent($e:Event)
    {
    // handle something
    }

    and

    private function onPhilMillClick($me:MouseEvent)
    {
    // handle something
    }

    I’m also that programmer who distinguish class vars with the almost forgotten primary expression keyword ‘this’.

    Now that I think about it, I’m not sure where the $ sign convention got started for me, I’m a Ruby on Rails guy. Maybe I should switch to @e … lol.

  173. Tracy says:

    Hi there

    I’ve recently started using inline functions for events where I can. The reasoning being that my class ends up with fewer methods. So for example:
    private function someFunction():void {
    // do some logic
    var myInlineFunction:Function = function(e:Event):void {
    someEventObject.removeEventListener(“someEvent”, myInlineFunction);
    // so some more logic here
    }
    someEventObject.addEventListener(“someEvent”, myInlineFunction, false, 0, true);
    }

    The extra parameters in addEventListener are probably overkill as I do manually remove the event listener. I’d be interested to find out whether there are any issues with this approach. I just find it localizes the logic in some cases, keeping my classes simpler, not having to deal with unrelated event methods.

  174. Darren says:

    Never use shorthand with naming, you should always be able to at any point in the code be able to identify the meaning and purpose of a variable. Always using naming such as ‘e’ would be acceptable if there was no other use besides events, but you also have errors and enumerations and plenty of others.

  175. Tracy says:

    I consistently use ‘e’ for Events & longhand for everything else, except things like iterators. I find rules are a good guideline but like to strike a balance btw rules vs a consistent non-verbose style.

  176. @Omar, that’s funny man, supreme intelligence huh? I’m w Lee though. 100% the best and most intuitive. And yes, I love using “e:”. Much quicker.

  177. And yes, your new design is nice man. Love the footer.

  178. Thiago Coelho says:

    up the e:Event

  179. private function bartStyle($event):void{
    // $ sign added on any parameter identifier is a must IMHO
    }

Leave a Comment