Be a Supporter!

Naming Conventions & code style

  • 1,131 Views
  • 16 Replies
New Topic Respond to this Topic
Yannickl88
Yannickl88
  • Member since: Nov. 2, 2008
  • Offline.
Forum Stats
Member
Level 11
Game Developer
Naming Conventions & code style 2009-08-21 14:23:53 Reply

AS3:MAIN

Naming Conventions & code style; What are they and why should you use them? I've been helping people on this forum for some time now and I see that some of the code that is posted is very confusing for a couple of simple reasons: naming of variables, class names and the way people format their conditionals.

First of all, everybody is entitled to their own way of coding and should do things the way they are most comfortable with. I'm not saying this is the only way, just giving some guidelines to help make it easier.

Naming Conventions. This is the way you name your variables and classes in the code. You say why? Well first of all it's about making a difference in what you mean with certain things. Is it a variable, class, function? It makes it easier to see this just by the name rather then looking it up somewhere hidden in your code. Here are the best practices:

Variables should always start with a lower case letter.
Classes should always start with an upper case letter.
Functions/methods should always start with a lower case letter.
Constants should always be upper case

Mainly when you specify a variable, class, function or constant, give it a name so people understand what it does.

var value1 = "hi"
var value2 = 10
var value3 = flashvars.name
var value4 = value2 + 1

This doesn't make a lot of sense right? You're better off picking some more meaningful names like these:

var welcomeText = "hi"
var visitors = 10
var username = flashvars.name
var newAmountOfVisitors = visitors + 1

See? it's right from the start clear what I was trying to store here. The same goes for classes and functions. It's useful to know what you can expect something is going to do or contains judging by the name.

Furthermore, make sure you CammelCase your names. This means that each word in the name should start with an uppercase letter. Say for instance you have a name like "myperfectexamplevariable" which is kind of hard to read in it's current state. Make it CammelCase like this: "myPerfectExampleVariable" Now it's easier to read.

Example:

package
{
    public class MyClass
    {
        public static const MYCONSTANT = "hello"
        
        private var myValue
    
        public function MyClass() //constructor, should be the same as the class name. So use an uppercase letter
        {
            this.setMyValue(MyClass.MYCONSTANT)
        }
        
        private function setMyValue(value)
        {
            this.myValue = value
        }
    }
}

var myClass = new MyClass()

That covers just about all the naming conventions. See how clear that made it? It's instantly clear what is a variable and what is a class name or constant. Even the build in flash classes use this. Just think about MouseEvent.CLICK. CLICK is a constant and MouseEvent is a class.

On to the following:

Code Style. Okay this is more of a personal preference, so I'll go over the most used styles of coding. Just as long you understand why is more important.

First, let's take a look at the previous example. This is a very spaced out way of coding. All the { and } are on their own line. Same goes for the if statements etc. This makes a more distinct way of letting the viewer see the difference between statement header (function bla(args)) and the body of a statement (what is between the { and } ). I, for instance, prefer this as I find it easier to read.

Second is as following:

function doSomething(arg1, arg2) {
    //...
}

Quite similar yes but it is a little more compact with the starting { on the same line as the function header. This one is very widely used, the PHP manual uses this for instance.

Bad Examples. Well that is about it, not much but just keep it clean and people will more easily understand what your are trying to do. Here are some examples I've seen recently of bad coding. I'm not trying to put people down so I'm not naming any or posting links, it's just examples.

function HowTo(MouseEvent) {
    howto.x=0;
    theX.x-=806;
}

Like what? MouseEvent is in this case a variable with the same name as a MouseEvent class. Very confusing. What if you want to create a new instance of a MouseEvent in the function...
and what is "theX"? X marks the spot?

players[0].addEventListener(MouseEvent.CLICK, Click);

function Click(event:MouseEvent){
    score = 2
    scorecounter.text = score;
}

So you're passing this mouse event to a class?... no wait it's a function... oh right.

onClipEvent(load){ moveSpeed=10;}onClipEvent (enterFrame) { if
(Key.isDown(Key.RIGHT)){    this._x+=moveSpeed; } else if
(Key.isDown(Key.UP)){    this._y-=moveSpeed; } else if
(Key.isDown(Key.DOWN)){    this._y+=moveSpeed;} else if
(Key.isDown(Key.LEFT)){    this._x-=moveSpeed;}}

Say what? oh wait, let's reformat that for you now.

onClipEvent(load)
{
    moveSpeed = 10;
}
onClipEvent(enterFrame)
{
    if(Key.isDown(Key.RIGHT))
    {
        this._x += moveSpeed;
    }
    else if(Key.isDown(Key.UP))
    {
        this._y -= moveSpeed;
    }
    else if(Key.isDown(Key.DOWN))
    {
        this._y += moveSpeed;
    }
    else if(Key.isDown(Key.LEFT))
    {
        this._x -= moveSpeed;
    }
}

Oooh, that makes a lot more sense. See, I did nothing to the code other than add some returns and indenting and it makes it so much easier to read.

Well, I think you've seen enough now. Just keep in mind that this is mostly personal taste apart from the naming conventions, those are pretty much a best practice among all coding languages.

So next time you post something here, let's make sure it's something we can read properly so we know what you are doing and can help you a lot better.

PS: I like to thank my friend Nano for spell checking this :D


You can ask me anything about AS3, PHP, HTML, CSS, JavaScript, Ruby, Python, Java, XML, JSON, Photoshop, and some more....

dELtaluca
dELtaluca
  • Member since: Apr. 16, 2004
  • Offline.
Forum Stats
Member
Level 20
Blank Slate
Response to Naming Conventions & code style 2009-08-21 17:33:59 Reply

I don't know why you've used AS2 in your final example if this is meant to be AS3 (Few other issues i might point out if i had more time), personally style is a very complex issue, I for example might rewrite your final example in the following manner:

onClipEvent(enterFrame)
{
    if     (Key.isDown(Key.RIGHT)) _x += moveSpeed;
    else if(Key.isDown(Key.UP   )) _y -= moveSpeed;
    else if(Key.isDown(Key.DOWN )) _y += moveSpeed;
    else if(Key.isDown(Key.LEFT )) _x -= moveSpeed;
}

Although speaking from a design point of view, the example is rather bad anyways, assuming it were to be used for the moment of a character; using the current if.else structure would be rather frustrating given that you cannot move diagonally, and that the various keys are given different weightings to the others; should you be holding down the down key for example, if you were to then hold the right key down, the right key is given more importance being higher in the chain of branches and would change the direction of movement.

I said i didn't have enough time, and yet wrote all that.

I might also note the lack of type declaration of any description in your first code sample, which while not relevant to the topic such as my above rant (I apologise for that) is something I feel could mislead individuals out of the good practive of typing variables.

-------

On a related note for once! I might also comment on the fact that you talk about only a signle naming convention, without comment on the other convetions such as Hungarian Notation (Where the type of the variable is a part of the name) such as:

var name:String = sName;
var age:int = iAge;
function fnMethod():void {}

etc. such that at any point in time, one can infer the type of the variable based solely on it's name without back tracking in a potentialy large piece of code to determine the type when working.


using ShamelessPlug; NapePhysicsEngine.advertise();

BBS Signature
JoSilver
JoSilver
  • Member since: Sep. 21, 2007
  • Offline.
Forum Stats
Member
Level 17
Melancholy
Response to Naming Conventions & code style 2009-08-21 18:02:50 Reply

Personally I like to name Booleans with all Capitals...

Yannickl88
Yannickl88
  • Member since: Nov. 2, 2008
  • Offline.
Forum Stats
Member
Level 11
Game Developer
Response to Naming Conventions & code style 2009-08-21 18:13:42 Reply

well my main reason for posting this was to let people have some guidelines as oppose to none at all. I know I havn't covered everything and all but it's better then nothing.

But yeah, it's all about personal taste, I put that in the beginning.

On a side note, yes I knew that was AS2 but it was about formatting not AS itself. Which actually goes for both. And it was part of the "Bad Examples." item, so yeah the code might not work at all. Like I said it was about formatting.

As for the type, yeah sorry about that. I started really coding with PHP, which the types are not (yet) really part of the coding standards. I always disliked them even in Java, they seem to limit my code and prolonged the time I was coding. Only reason I see use for them is in the code completion of the IDE and since flash's code completion is total shit. I don't use them at all, makes the code cleaner, readable and faster to write.
Yeah yeah I know, bad coding. Well I don't care, if you cannot use your own functions properly, there is something wrong with you. Not the code.


You can ask me anything about AS3, PHP, HTML, CSS, JavaScript, Ruby, Python, Java, XML, JSON, Photoshop, and some more....

dELtaluca
dELtaluca
  • Member since: Apr. 16, 2004
  • Offline.
Forum Stats
Member
Level 20
Blank Slate
Response to Naming Conventions & code style 2009-08-21 18:21:00 Reply

At 8/21/09 06:13 PM, Yannickl88 wrote: Well I don't care, if you cannot use your own functions properly, there is something wrong with you. Not the code.

You don't understand the benefits of variable typing clearly, typing variables means that the the compiler (However shit it might be) knows the type at compile time and you benefit from increased run time performance, aswell as being able to debug code a lot more easily (And don't tell me that only bad programmers need to debug, no matter how good are you, typos are a bitch!)


using ShamelessPlug; NapePhysicsEngine.advertise();

BBS Signature
Yannickl88
Yannickl88
  • Member since: Nov. 2, 2008
  • Offline.
Forum Stats
Member
Level 11
Game Developer
Response to Naming Conventions & code style 2009-08-21 18:42:25 Reply

You might be right. But is it really that much? With the current PC's, would one notice it really?

Prove me wrong and I'll add it to every line of code I have in flash. But until then I'll just leave my types gone as they are.


You can ask me anything about AS3, PHP, HTML, CSS, JavaScript, Ruby, Python, Java, XML, JSON, Photoshop, and some more....

FlukeDude
FlukeDude
  • Member since: Sep. 18, 2006
  • Offline.
Forum Stats
Member
Level 14
Blank Slate
Response to Naming Conventions & code style 2009-08-21 19:00:38 Reply

At 8/21/09 06:42 PM, Yannickl88 wrote: With the current PC's, would one notice it really?

With a game that has a lot going on - yes. Even with current PCs it's still running through a browser.


They used to call me souled...

Cojones893
Cojones893
  • Member since: Mar. 9, 2003
  • Offline.
Forum Stats
Member
Level 22
Blank Slate
Response to Naming Conventions & code style 2009-08-21 19:01:44 Reply

At 8/21/09 06:42 PM, Yannickl88 wrote: You might be right. But is it really that much? With the current PC's, would one notice it really?

Prove me wrong and I'll add it to every line of code I have in flash. But until then I'll just leave my types gone as they are.

I'm running some quick tests because I can't find the document I had written on speed testing.

var b = 0; //226ms
vs:
var b:int = 0; //52ms

for (var i = 0; i<10000000; i++) {} //238ms
vs:
for (var i:uint = 0; i<10000000; i++) {} //51ms

It can be many many many times faster to know what type you are going to give it. Never say that a fast computer will make up for shitty programming practices.

knugen
knugen
  • Member since: Feb. 7, 2005
  • Offline.
Forum Stats
Member
Level 42
Programmer
Response to Naming Conventions & code style 2009-08-21 19:42:56 Reply

At 8/21/09 06:02 PM, JoSilver wrote: Personally I like to name Booleans with all Capitals...

Everybody have their personal preferences, which is ok as long you're the only one reading the code, but that convention is very tightly associated with constants. Perhaps that's what you meant though, because I fail to see much logic behind using it for booleans? ;P

Yannickl88
Yannickl88
  • Member since: Nov. 2, 2008
  • Offline.
Forum Stats
Member
Level 11
Game Developer
Response to Naming Conventions & code style 2009-08-22 04:00:13 Reply

quite a differance in speed there. Well that proves it then, never knew really.

*addes types to his current game*


You can ask me anything about AS3, PHP, HTML, CSS, JavaScript, Ruby, Python, Java, XML, JSON, Photoshop, and some more....

GustTheASGuy
GustTheASGuy
  • Member since: Nov. 2, 2005
  • Offline.
Forum Stats
Member
Level 08
Blank Slate
Response to Naming Conventions & code style 2009-08-22 04:37:40 Reply

You are aware that in AS code lines are delimited by a semicolon, Mr.Conventions?

As for typing, sure there isn't a visible slowdown, but that doesn't mean it isn't running a hundred times slower than it should. Just because you can't be arsed declaring whether a variable is an int or a Number, the runtime has to wrap it in a dynamic type and make hidden conversions every time you do a numeric operation. As can easily be seen, this already makes code ten times slower.
But numbers are just the start, checking if objects are the right type dynamically is much more involved. As well as accessing properties of an untyped object.


BBS Signature
Deadclever23
Deadclever23
  • Member since: Nov. 27, 2006
  • Offline.
Forum Stats
Member
Level 12
Blank Slate
Response to Naming Conventions & code style 2009-08-22 05:04:49 Reply

At 8/22/09 04:37 AM, GustTheASGuy wrote: Stuff.

Which is also why they introduced vectors instead of just keeping with arrays.


"To live is the rarest thing in the world. Most people exist, that is all." - Oscar Wilde

BBS Signature
Yannickl88
Yannickl88
  • Member since: Nov. 2, 2008
  • Offline.
Forum Stats
Member
Level 11
Game Developer
Response to Naming Conventions & code style 2009-08-22 15:47:35 Reply

Gust, yes I know. But as far as I am aware they are "optional". Sure probably the compiler again.

Ah well, I'll just refrain from posting this sort of things next time... seeing as how many people are questioning it.


You can ask me anything about AS3, PHP, HTML, CSS, JavaScript, Ruby, Python, Java, XML, JSON, Photoshop, and some more....

GustTheASGuy
GustTheASGuy
  • Member since: Nov. 2, 2005
  • Offline.
Forum Stats
Member
Level 08
Blank Slate
Response to Naming Conventions & code style 2009-08-22 16:40:13 Reply

They're optional, but again it doesn't mean you should exclude them.

You don't need to refrain from posting, because it also helps you yourself better understand the things you're talking about. And you get feedback. So keep doing it.


BBS Signature
Yannickl88
Yannickl88
  • Member since: Nov. 2, 2008
  • Offline.
Forum Stats
Member
Level 11
Game Developer
Response to Naming Conventions & code style 2009-08-22 17:02:55 Reply

You might be right, shame there is no edit button. Else I would have cleaned up my initial post.

PS: refactoring my current game project to include all the types and semicolons, just so you know I did learn a thing or two ;).


You can ask me anything about AS3, PHP, HTML, CSS, JavaScript, Ruby, Python, Java, XML, JSON, Photoshop, and some more....

GustTheASGuy
GustTheASGuy
  • Member since: Nov. 2, 2005
  • Offline.
Forum Stats
Member
Level 08
Blank Slate
Response to Naming Conventions & code style 2009-08-22 17:06:58 Reply

That's not really refactoring since you're not changing anything. Make sure you're not wasting your time.


BBS Signature
Yannickl88
Yannickl88
  • Member since: Nov. 2, 2008
  • Offline.
Forum Stats
Member
Level 11
Game Developer
Response to Naming Conventions & code style 2009-08-22 17:25:46 Reply

At 8/22/09 05:06 PM, GustTheASGuy wrote: That's not really refactoring since you're not changing anything. Make sure you're not wasting your time.

Well it is in my case, since I need to add some more inherentance here and there for better type safe params etc. And in the end it is nicer and maybe a little faster. In any case it's just good practice to add them anyways.


You can ask me anything about AS3, PHP, HTML, CSS, JavaScript, Ruby, Python, Java, XML, JSON, Photoshop, and some more....