Open Mike: Prefixes

Open Mike: Prefixes

To underscore, or not to underscore? This is Open Mike, a series of discussion posts to throw the cat amongst the pigeons. These posts are all about you — we want to hear your opinions, ideas, and thoughts. Due to popular demand, this Open Mike includes a poll to help us analyze opinion, so let’s hear what you have to say about prefixes.


Do You Put Underscores Before Variables?

AS3 developers often use underscores as prefixes for private or protected variables in a class:

private var _playerID:String; 

Some coders find this a useful way to tell at a glance whether the var is available to other classes; others deride it as useless and ugly. Whose side are you on?


How About Method Arguments and Interfaces? What Else?

Other common prefixes are a_ for method arguments (or p_ for parameters), and I for interfaces.

public function takeDamage(a_damage:Number):void
{
	_damage-=a_damage;
}
package
{
	public interface IPlayerCharacter
	{
		function takeDamage(a_damage:Number):void;
	}
}

The “I for interface” prefix is pretty common, but argument prefixes are rarer.

Any others you use often? Let us know in the comments.


Hungarian Notation: Yea or Nay?

If those didn’t bring out strong opinions, I’ve got two words for you: Hungarian notation.

No, I’m not talking about Systems Hungarian, where the data type of the object is encoded into a prefix of the name:

var intCounter:int = 0;
var boolBestScore:Boolean = false;
var nHeight:Number = 120;
var btnOK:SimpleButton = new Button();

No-one’s still using that, are they? With a decent IDE you can tell the data type of any variable easily; there’s little need to have that information in the name of the variable.

I’m talking about Apps Hungarian, where the purpose of the object is encoded into a prefix of the name:

var dHeight:Number = newHeight - oldHeight;	//d for 'difference'
var cChildren:int;	//c for 'count'
var degAngle:Number;	//deg for 'degrees'
var radAngle:Number;	//rad for 'radians'

(Check out Joel Spolsky’s excellent article Making Wrong Code Look Wrong for more information on this.)

Do you use any form of Hungarian notation, or is it completely unnecessary in an OOP language like AS3?

  • http://www.midnyt.net Midnyt

    I probably voted for all the bad answers… No, no, no, I like Systems Hungarian.

    Though technically, if I wrote more classes instead of just code on the first frame of the timeline, then I’d probably use the underscore for private variables.

    • http://michaeljameswilliams.com/ Michael Williams
      Author

      Interesting.. yeah, I can see that you’d have different habits as a timeline coder than as a class coder. I wonder what else would be different?

  • http://iqandreas.blogspot.com/ Andreas Renberg

    > Do You Put Underscores Before Variables?
    I only put underscores in front of private variables related to getter/setters, where the “non-underscored” name is already taken, preventing naming conflicts.

    Most of my private variables are already obvious why they are private, and therefore don’t need any further clarification. Also, if I decide to change a variable from a private var to a function parameter instead, I would need to remove the underscore from all references. I rarely (if ever) change private variables to public ones, but instead create getter/setters for them, so that type of name change is rarely an issue.

    > How About Method Arguments and Interfaces? What Else?
    For Interfaces, I use a standard “I” prefix (and I feel like Apple’s naming committee every time I do so)

    For parameters, I use no special notation, which maybe isn’t the best, because I have some code where I need to clarify the difference between a public property and the function parameter (most often in the constructor)
    public function Car(color:Color, size:int):void //Constructor
    {
    //”this.color” refers to the getter/setter, while the “color” refers to the function parameter. :(
    this.color = color;
    this.size = size;
    }

    As for others, I tend to name all BitmapData variables something like “originalBMD” or “monaLisaBMD” and sometimes use the “BMP” for bitmaps if they are closely tied to the BitmapData.

    > Hungarian Notation: Yea or Nay?
    Systems Hungarian, no. What if down the line you decide to change the “int” to a “Number” instead? Variable renaming with Find and replace is handy, but can cause some unexpected changes to your code, and should therefore be avoided, not to mention the confusion of changing names mid-code.

    Apps Hungarian, yes, on occasion. I don’t adhere to it super strictly, but if it makes the purpose of the variable more clear, then I use it. For instance, I may name an array of instances “instances” or “instances”, but the amount of children in that array “numInstances”. So in that case, naming the “count” variable “instances” instead would be very misleading.

    Anyway, that’s my $4 (I think I wrote too much for it to only total 2 cents) of strongly opinionated coding styles. :P

    So what about you, Mike? What standards do you use?

    • http://michaeljameswilliams.com/ Michael Williams
      Author

      Wow, thanks for the massive comment :)

      I use underscores before all private/protected vars, “a_” before method arguments, “I” before interfaces, and Apps (but not Systems) Hungarian. Big fan of Apps Hungarian, actually.

      I feel I should start using “this.” by default whenever referring to a class’s variables, like you do, but I haven’t forced myself into the habit yet. “this.color = color” still makes me wince, though! I guess that’s why I like “a_” as a prefix; no confusion between variable scope. Plus, with autocomplete, I can type “a_” and it’ll show me the names of every argument passed to the function I’m working in.

      Ah, so you use something kinda like Hungarian notation for your BitmapData, only as a suffix rather than a prefix ;) I do the same thing to show BMDs and BMPs; also for XMLs and other cases where there are two related objects of different types.

      I suppose with your “instances” example I would call the counter “cInstances”. Actually, that’s a lie, I’d probably call it “i” out of laziness, but I want to call it “cInstances” ;)

  • http://www.giuliandrimba.com/blog Giulian Drimba

    *Do You Put Underscores Before Variables?

    If the variable will be acessed through get and setter, I put underscore before de private variable, if not, I don’t put any.

    *How About Method Arguments and Interfaces? What Else?

    Method arguments I don’t put any prefixes, and interfaces I put the “I” as a prefixe.

    • http://michaeljameswilliams.com/ Michael Williams
      Author

      If the variable will be acessed through get and setter, I put underscore before de private variable, if not, I don’t put any.

      That’s neat — a way to tell, instantly, whether the variable you’re dealing with is in some way accessible by other classes.

  • http://www.karlfreeman.co.uk Karl Freeman

    “All Hungarian notation is a sin” – I’d take longer variables names ( auto completed ) than a system of random prefix’s. Take the perfect example of using just a d infront of something.

    trace(“” + dAngle);

    At glance if you were to stumble across this in your class, is the d for distance? could be degrees?. In fact it could be deduction or even defined.

    Hell d could even mean destination.

    • http://michaeljameswilliams.com/ Michael Williams
      Author

      I take your point. I like long variable names too, but short prefixes are really useful as metadata — as long as they’re consistent.

      What would you call your vars if you stored some angles as radians and some as degrees? (Perhaps because some were used for trig calculations while others were for rotating Sprites.)

  • http://scarybuggames.com Scarybug

    I’ve taken to using underscore prefix for getter/setter privates and also for temporary variables inside methods so I remember they have a different scope.

    I haven’t found separating public and private variables that useful, and I tend to occasionally promote a protected or private variable to public anyway.

    I’ve also started using a $ as a prefix for function parameters. Not sure where I picked that up, but I like it.

    I don’t like Hungarian notation because all variables should be all underscore_separated_lowercase, only functions should be camelCase and classes should be CamelCase. (and constants or magic number holders should be ALL_CAPS

    This is especially useful in a language like AS where you can pass functions and class names around as variables, so you don’t always know based on context.

    • http://michaeljameswilliams.com/ Michael Williams
      Author

      Huh, you use underscores for all vars? I’ve not seen that often. We have another post lined up to talk about that ;)

      I quite like the idea of using a $ for function parameters, thanks for that :)

  • http://www.woutr.be Wouter De Loose

    “Do You Put Underscores Before Variables?”

    Only when they need a getter / setter, otherwise there is no need to put an underscore before the variable.
    If I see an underscore in my code, I know there is a getter / setter for that variable.

    • http://michaeljameswilliams.com/ Michael Williams
      Author

      Neat!

  • http://www.zacktbrown.com Zack Brown

    I only put underscores in front of private variables. And only so I can tell the difference between the private variable and his getter/setter. I won’t do it for protected.

    I don’t do Hungarian notation. I agree with Karl, I think it makes for less readable code.

    • http://michaeljameswilliams.com/ Michael Williams
      Author

      Same kinda thing as Wouter then?

  • http://johnpolacek.com John Polacek

    Nobody’s perfect, but I try to stick to the Flex SDK coding conventions and best practices document as much as possible:
    http://opensource.adobe.com/wiki/display/flexsdk/Coding+Conventions

    Scarybug brings up a trend I have noticed where $ as a prefix is used to identify function parameters. I don’t know how I feel about this. On the one hand, I can see how it would help you keep your vars straight, but on the other hand it goes against common custom and that $ really stands out like an eyesore to me when I see it. I’d like to hear some better arguments against it though.

    • http://michaeljameswilliams.com/ Michael Williams
      Author

      I bet it would stop being an eyesore after a while. I used to dislike the underscores for the same reason, but I got used to them.

  • RCDMK

    I never use underscores for private variables. I prefer to use them starting with a lowercase letter and for all the public stuff I use uppercase: the private wold be “numLives”, while the property wold be “NumLives”. It just make more sense to me.

    About prefixing parameters… Sometime ago I often use only an underscore to prefix parammeters and the “this.lives= _lives” for the assignment. Now I just use the “this.lives = lives”.

    A long time ago I’ve used hungarian notation. Today, with all theses IDEs, I just type the name without any prefix or sufix, but XML and some other rare types.

    • http://michaeljameswilliams.com/ Michael Williams
      Author

      Interesting — lowercase private, uppercase public is how C# does it. Did you come from a .NET background?

  • André

    To say the truth, sometimes i use underscore before a private/protected variable… the correct is not to use, and the function parameters are not the same as the private classes…

    For example;
    package{
    public class Main(){
    private var testvar:String=”mytestvar”;
    public function testfunction(testvar:String):void{
    trace(testvar==this.testvar); //if you pass the parameter “mytestvar” it will return true, otherwise false…
    }
    }
    }

    var instance=new Main();
    instance.testfunction(“mytestvar”); //true
    instance.testfunction(“othervar”); //false

    So there is no reason for use _ (underscore) before variables, but sometimes i use…

    • http://michaeljameswilliams.com/ Michael Williams
      Author

      What do you mean by “the correct is not to use”?

      Do you always use “this”? I find it confusing to do things like your “testvar” example otherwise :/

  • Casey

    I use underscore to precede anything that is accessed or invoked indirectly. So, that would apply to get/set internal vars as well has methods that are only invoked by EventDispatchers etc, like so:

    function get foo() : int {
    return _foo;
    }

    addEventListener( “bar”, _onBar );

    Just sayin’

    • http://michaeljameswilliams.com/ Michael Williams
      Author

      So an underscore says, “you should never access this directly”? Nice idea.