9 Confusing Naming Conventions for Beginners
basix

9 Confusing Naming Conventions for Beginners

Especially when first getting started with various web development languages, it can prove to be a difficult task to learn all of the various naming conventions from language to language. This can be even more confusing when developers disagree on what’s considered best practice. To help ease the transition for beginners, this list will describe some of the more common conventions.


1. Underscore Before the Property Name

When you come across a variable or method that is proceeded by an _, there’s no voodoo magic being performed behind the scenes. It’s simply a naming convention that reminds the developer that the variable/property/method is either private or protected, and cannot be accessed from outside of the class.

PHP Method

// This variable is not available outside of the class
private $_someVariable;

class MyClass {
   // This method is only available from within this class, or
   // any others that inherit from it. 
   protected function __behindTheScenesMethod() {}
}

Note that, in the code above, the underscore is not what makes the variable or method private; the private/protected keyword does that. The underscore is only a reminder for six months down the road!

JavaScript Method

var Female = (function() {
   var _trueAge = 50,
        _trueWeight = 140;

   return {
      age : _trueAge - 15,
      weight : _trueWeight - 30
   };  
})();

Female.age; // 35
Female.weight; // 110
Female._trueAge; // undefined (cause it's private, yo)

By making Female equal to, not a function, but the returned object, we can create private variables. Again, the underscore prefix reminds us of this.


2. UPPERCASE Constants

A constant is a variable with a static value, that won’t change. For example, if your project required the need to multiply a value by the state tax, you might assign this rate, $.0825 to a constant. However, not all languages have these variable types built in. As such, it’s a best practice to use all capital letters to remind yourself that you’re working with a constant. This is a common convention in the JavaScript world, and is used its native objects, like MATH.PI.

JavaScript Method

var TAXRATE = .0825;

PHP Method

define('TAXRATE', .0825);

3. Single Letter Prefixes

You’ve surely, at some point, come across a variable that was proceeded by a single letter, such as "s" or "i".

$sName = 'Captain Jack Sparrow';

This is referred to as Hungarian notation, and has fallen out of favor in recent years, though it’s still a convention that’s used by many companies.

Hungarian notation is a naming convention that reminds the developer about the type of variable that he’s working with: string, integer, etc.

Particularly in the JavaScript world, this practice is frowned upon, due to the fact it’s a loosely typed language. A loosely typed language is one that doesn’t require you to declare the data type of a variable. Why is that significant? What if, using the notation convention above, we declared a string with the "s" prefix, but then later changed the variable to an integer? At that point, this form of notation would in fact work against us, not for us.

var sName = "Lieutenant Commander Geordi La Forge";
typeof(sName); // string
....
sName = undefined;
typeof(sName) // undefined

The Dollar Symbol

jQuery users: before you step on your pedestal and praise yourself for not using this form of notation, ask yourself if you prefix variables – wrapped in the jQuery object – with a dollar symbol? If so, that’s a form of Hungarian notation. It’s a symbol prefixed to a variable name which serves the sole purpose of informing you of the variable’s type or qualities.

// The dollar symbol reminds me that this variable
// has access to jQuery's various methods. 
var $container = $('#container');

Should You Use It?

That’s entirely up to you. Even many jQuery team members use the dollar prefix method. Ultimately, if it works for you, that’s all that matters. Personally, as of about a year ago, I don’t use the dollar symbol prefix any longer — but only because I realized that it wasn’t necessary for me. Make up your own mind on this one.


4. Capital First Letter

What about those “variable” names, which capitalize the first letter of the name?

$response = $SomeClass->doSomething();

In the code above, $SomeClass is capitalized because it is a class and not a variable name. Again, this is a naming convention that most developers use. When returning to the code a year later, it’s a small lightbulb that informs them that they’re working with a class, which has objects and methods available.

// Note the capital M in the class name. 
class $MyClass {
   function __construct() {}
}

The JavaScript World

In JavaScript, we don’t really have classes; but we do have constructor functions.

var Jeff = new Person();

The reason why we capitalize the name of the constructor (Person) is because it can prove easy to sometimes forget the new keyword. In these circumstances, JavaScript won’t throw any warnings, and it can be a nightmare to track down the glitch. The capitalization is a helpful alert for the developer, when debugging. Douglas Crockford is a big advocate of this convention.

Alternatively, if you want to protect against your future self’s forgetfulness, you could first ensure that the constructor is, in fact, correct, before proceeding.

function Person(name) {
  // If the new keyword is absent, the constructor will be the window.
  // In this case, compensate, and return a new instance
  if ( this.constructor !== Person ) {
    return new Person(name);
  }
 this.name = name;
}

// Intentionally forgot the "new" keyword 
var Joey = Person('Joey');
Joey.name; // Joey

5. CamelCase vs under_score

Why is it that some variables use a camelCase pattern,while others use an underscore to separate words? What’s the correct method? The answer is there is no correct usage. It entirely depends on the language, and/or your company’s coding conventions. Both are perfectly acceptable.

// camelCase
var preacherOfSockChanging = 'Lieutenant Dan';

// under_score
var preacher_of_sock_changing = 'Lieutenant Dan';

However, with all that said, it’s a best practice — when you have the option — to follow the common conventions of the language you’re using. For example, the large majority of JavaScript developers use the camelCase syntax, while other languages, like PHP, tend to prefer the underscore usage. Though, again, this isn’t set in stone. The Zend Framework advocates camelCasing as a best practice.

More important than what you use is ensuring that you stick to it!


6. Directory Structure

Particularly when working on a team, it’s essential that you adopt the proper directory structure as your fellow developers. But, at the very least, certainly don’t drop all of your stylesheets and scripts into the root of your project, without any organization. Many developers prefer to place all of their images, scripts, and stylesheets within a parent Assets directory.

/ Project Root
  /Assets
    / js
      / min
        script_min.js
      script.js
    / css
      / min
        style_min.css
      style.css
    / img
      img1.jpg
  index.html
  otherFile.html
  

Also, note the convention of also creating a min folder, which contains the dynamically added minified versions of your scripts and stylesheets.


7. Semantics

When creating mark-up, hopefully, it’s widely understood that the ids and classes you choose should describe the type of content, and not the presentational aspects. As an example:

Really Bad

<div id="middle-left-and-then-a-little-lower"> Justin Bieber is my homeboy section. </div>   

Better

<div class="section"> Justin Bieber is my homeboy section. </div>   

Best

<section> Justin Bieber is my homeboy section. </section>

How come? What if, six months down the road, you decide to place your Justin Bieber fan section in the middle-RIGHT-and-then-a-little-lower section? At that point, your id will make little sense.

As we transition into an HTML5 world, you should find yourself using far fewer identifiers in your elements. ids are less flexible, and are many times unnecessary.


8. Double Headers and Footers

You know what stinks? When working on a centered website that requires multiple backgrounds that extend for the entire width of the window (usually for the header and footer), you typically have to wrap your content so that the outer element will extend, while the inner element can remain centered.

As this is a common issue, it's important to adopt a common convention for creating the necessary mark-up.

<div id="footer-wrap">
	<footer>
	  My footer content goes here.
	</footer>
</div>   

The difficult decision here is that, assuming you're working with the new HTML5 elements, you have to decide whether to place the footer element on the inside or the outside. It's still up for discussion, however, I tend to feel that it's more semantic to place the actual footer element on the inside.

divs should be used only when:

  • There's no better element for the job
  • When your need of the element is purely to structure a layout

9. Shortcuts

Decide now whether or not you're going to allow the use of shortcuts in your code. Writing precise/clean code is always a battle of readability vs. size. This is why it's paramount that development teams follow the same coding guidelines. To provide two quick examples:

Is the Ternary Operator Okay with You?

var name = 'Joe';

// regular
if ( name === 'Jeff' ) {
  alert("That's me");
} else {
  alert("Nope");
}

// ternary
(name === 'Jeff') ? alert("That's me") : alert("Nope"); // Nope

What About the Logical && For Short-Hand Conditionals?

var getTweets = true;

// regular
if ( getTweets ) {
 alert('getting them now');
}

// Logical AND
// Right-side won't run, unless left-side is "true"
getTweets && alert('Getting them now');

Many developers will frown upon the use of the logical AND in this case, insisting that it limits readability. This is certainly a valid argument, though, nonetheless, even popular libraries like jQuery make heavy use of this method.


Conclusion

To reiterate, the specific conventions you choose are far less important than ensuring that you remain consistent with your usage. In fact, many development teams write their own convention guidelines for new dev hires. Thanks for reading!

Tags: basix
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Eduardo Barros

    Great tutorial, but this was really funny: “Justin Bieber is my homeboy section.”

  • http://spotdex.com Davidmoreen

    Pretty interesting, I actually didn’t know about the capital first letter variable for an object. I’ll have to start to use it!

  • http://www.theunusableweb.com/ Sam

    Hungarian Notation was originally not intended to denote the data type (string, int, etc.) of variable. Apps Hungarian (the original form, developed by Charles Simonyi) was used to store semantic information. For instance, wX vs dX would indicate the x-coordinate for the window and document (respectively) in Microsoft Word.

    Many web programmers use Apps Hungarian to indicate if a variable is safe (s) or unsafe (u), thus ensuring user input is sanitized before use (it becomes obvious your data needs to be sanitized when you’re about to send u_username to a database).

    Systems Hungarian (later developed by the Windows team as a bastardization of Apps) indicates the data type of the variable. It’s really rather useless.

    • http://recklesswaltz.deviantart.com/ Shesh

      It drives me crazy when I see code using the Systems Hungarian notation for no real reason at all!

      It’s written in more detail here: http://joelonsoftware.com/articles/Wrong.html (skip to the “I’m Hungary” part)

    • Frankie Lee

      Dear Mr. Simonyi moved already in the early eighties to Microsoft and i maybe he himself who influenced the development of the bastardization of Apps. However, the actual MS general naming conventions state clearly: “Do not use Hungarian notation.”

      I have to say i used the Apps Bastardization for most projects when i was a Java developer about a decade ago and i am happy i got rid of this habit.

  • Anthony

    I think “Capital Letter First” is Pascal Case. I could be wrong though because I didn’t do a confirmation search. All I know is that Pascal Case is what the developers at my work refer to it as.

  • http://www.wordimpressed.com/ Devin Walker

    Great read! Thanks, taught me a bit about naming conventions!

  • http://www.umbraprojekt.pl mingos

    “The Zend Framework advocates camelCasing as a best practice” – but only for function naming. Note that class names use underscores, which reflect the directory structure of the project. I think they’re mandatory. Also, Zend’s inbuilt classes also use underscores. And sometimes, they mix the two conventions in the same name:

    $elt = Zend_Form_Element_Text(‘email’);
    $elt->addValidator(new Zend_Validate_EmailAddress());

    There’s a logic behind that, though :).

    • http://www.umbraprojekt.pl/ mingos

      err, forgot a “new” there:
      $elt = new Zend_Form_Element_Text(‘email’);

      :D

    • http://www.seven-sigma.com/ Jeff Dickey

      ZF is an incredibly powerful tool, sort of like a nuclear-powered chainsaw without an ‘off’ switch. Like such a chainsaw, you either quickly master it in fullness or you find little bits and pieces of yourself and your project scattered over sixteen time zones.

      The naming convention you mention makes perfect sense, once you sit and think about it for a minute. (underscores equate to directories, pseudo-namespaces in pre-5.3 PHP; CamelCase is used within a single name segment. But that’s one more thing you have to remember when you’re coding and think about when you’re reviewing.

      (Personally, I’m glad they don’t use namespaces. I’ve seen a dozen or so languages that implement some moral equivalent of namespaces, and none of them use notation as ugly/unreadable as PHP’s.)

  • http://www.freshclickmedia.com Shane

    Everybody has an opinion on naming conventions don’t they?! The C# projects I’ve worked on have always had a mixture of styles, which is bad for a number of reasons. I can often spot a C# developer who’s formerly developed in VB.NET or C++, since they’ll often carry over styles into C#.

    Consistency is key, but I strive to apply naming conventions that are specific to the language I’m using. So, I’ll style differently if I’m writing PHP, rather than C#, let’s say.

    I’ve even seen different naming conventions used for different local variables, all declared on adjacent lines! Talk about sloppy!

    Good selection of guidelines though.

  • http://www.chriskdesigns.com Chris

    This is a must read for anyone who is trying to learn best practice with their selected language. Recently I’ve had the opportunity to work closely with two colleagues who have many years in the development field and have learned so much of what is considered ‘best practice’.

    Book mark this one for sure.

  • http://visual-blade.com Daquan Wright

    Interesting read, the underscore vs. camel case argument always had me wondering. I just decided to go with camel case, ultimately it’s what I prefer. Though using particular coding conventions based on the language isn’t a bad idea either.

  • http://evansofts.com evanxg

    I really prefer camel case notation and stick to it in any of those language : c++, c# , Java , Php and JavaScript. unless my team require another convention.
    And I think it is the most popular in nowadays projects.

  • temp01

    The ternary one (#9) should be:
    alert(name === “Jeff” ? “That’s me” : “Nope”); // Nope

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Yeah – that’d be fine too, assuming an alert either way.

    • jpope

      I agree the #9 ternary example given is “improper.” temp01′s is the proper use for the ternary operator. The example #9 ternary case is a dirty hack like the && case, but it could be made proper as temp01 shows.

      Personally, I don’t like either of #9 examples, and I think they go against “best practices.” So for any one looking for best practice advice (as it seems many comments reflect) I’d recommend avoiding #9, and just use that information to help you understand what it means if you come across it in someone elses code.

      • http://www.wdonline.com Jeremy

        Remember the context of this article: it’s for beginners. Both examples in #9 are appropriate in this context; they are clear examples that show how a simple if…else converts to a ternary operation.

  • http://jiewmeng@gmail.com Jiew Meng

    I find “middle-left-and-then-a-little-lower” funny LOL

    • http://jiewmeng@gmail.com Jiew Meng

      Oh, and I prefer camelCase to underscrore. and shortcuts sparingly, just for short bits of codes

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Heh – that was the plan.

  • http://buyeyeglasses.com Tamik

    I think there is an error in code in header #4 : Capital First Letter.

    class $MyClass {
    function __construct() {}
    }

    i think the dollar sign in front of class name is not right…

    • http://edrackham.com Ed Rackham

      I think you’re right Tamik!

      Nice article throughout though.

  • Aymen BEN

    (name === ‘Jeff’) ? alert(“That’s me”) : alert(“Nope”); // Nope

    There is something wrong with the coloring, I think it’s because of using ‘ unstead of ’ or the oposite.

  • http://www.wplancer.com Banago

    Great article. As a PHP coder, I prefer underscore convention over camelCase; I find it far more legible and nice to look at.

    • http://programming-on-purpose.blogspot.com/ Brandon

      I just started working on a project that uses Doctrine ORM. Doctrine uses camelCase, while Kohana (the framework that I write most of my apps in) uses underscore. I completely agree with you, I find underscore convention to be a lot easier to read.

  • Andrei Sfat

    Nice article! Keep up the good work :)

  • David Beveridge

    One more javascript shortcut to include: the OR short hand.

    It works the oposite of && shorthand. The right side will only run if the left evaluates as false:

    var name = alreadyDeclaredName || ‘Bob’;

    There’s also a PHP shortcut that your development team may or may not want to use:

    if($myVar = myFunction()) { … }

    It’s handy if you need to assign a value and then check it, but I have had people object to this usage because it wasn’t immediately clear what was happening.

  • http://www.dev-hq.co.uk/ Joe

    Great article!
    Very useful – keep up the good work!

  • http://www.deepbass.com/portfolio Brad Shaw

    I think the logical choice for 8 isnt to wrap the footer but to use the footer as the wrapper. You could have several divs within the footer with links, contact info, copyright, etc. and so the right way IMO would be to do something like:

    My footer content goes here.

  • http://osura.com Anton Korzhuk

    really enjoyed reading this one. learned a few things too ;)

  • http://www.keyboard-computer.com Keyboard

    Yep!
    Very usefull for begginers :)
    Thx!

  • http://www.20milesnorth.com Christina Web

    When we finally get to full HTML 5 conversion those short tags instead of garbage is going to save a lot of keystrokes for website designers/coders

  • http://submitlinks.biz sarah

    great information.. thanx for usefull info.

  • http://www.eclipsedesign.eu Kartlos Tchavelachvili

    I am reading here golden tips :D thanks!

  • http://johan.notitia.nl/ Johan de Jong

    I have to disagree to the first point “Underscore Before the Property Name”. Single underscores before a property seems OK, but double underscores refer to magic properties (http://php.net/manual/en/language.oop5.magic.php) and should not be used to prevent compatibility problems with future PHP versions.

    It’s better to use prefixes, which have the same effect on recognition.

  • http://prop-14.com Randy

    The one I always get confused about is the double dollar sign in php. $$value['id']

    Off topic: So now Justin B will be the story behind every single tutorial? Not sure how many 12 year old girls are followers of this blog? I’d kind of rather be targeted as a slightly higher educated group.

    Sorry, I just hate that little f….

  • http://www.how-to-asp.net Ryan

    I love some of these articles that go back to the basics, it reminds me of why I do things a certain way. Thanks for sharing!

  • C.F. Action

    Great read…. Thanks for the post!

  • http://www.walkomedia.com Guy Arbus

    Back to the basics !
    Very useful, so smart !
    I love all these articles that speak about guidelines in webdesign. Great Job.

  • Monkeytail

    The conventions I stick to across the ‘big 4′ (html/css, js, php)

    id=”first-name” (html/css)

    name=”first_name” (php)

    onload=”firstName” (js)

  • http://nixtu.blogspot.com Juho Vepsäläinen

    Nice collection of tips!

    Depending on your coding conventions you might want to use camelCase to represent methods while lower_case is used for functions. Sort of handy. I use this convention in Python (see PEP-8). I stick to pure camelCase in JS though.

    Regarding ternary and such sometimes you may use a Null object to avoid extra checks. A Null object just provides the same interface as the real one. It does nothing else.

    Who the heck is Justin Bieber?

  • http://www.red-team-design.com Red

    Great tips, thanks for sharing!

  • http://imp.airy.me IMP

    getTweets && alert(‘Getting them now’); – great!

  • http://imp.airy.me IMP

    IF-THEN-ELSE alsow works like this:
    condition && fn() || fn2()

    Personally I use
    CapitalCase for Classes
    camelCase for methods and functions
    under_scores for variables

  • http://mixmo-anime.blogspot.com kankuro

    This is great article to read…….

  • http://phpdojo.blogspot.com/ Goran Miskovic

    Basically, all naming conventions and practices are there to remind developer on something. I feel that in age of modern IDE applications such need is at least archaic. For example, I see no need in placing underscore in the front of private/protected variables/methods since those are already clearly annotated by IDE. Adding underscore just makes visual noise.

    • jsc42

      You cannot assume that everyone uses an IDE or uses a language that include private / protected keywords. Any programmer worth his / her salt should be able to programme in a text editor (Notepad / vi / ISPF) at least as fluently as in an IDE; otherwise they will struggle doing remote diagnostics / patching over a terminal emulator. Personnally, I do everything in text editors as IDEs are so expensive, resource hungry, idiomatic or are just not on the approved lists of products in closed environments.

      A couple of days ago, I came across the term ‘snake_case’ to describe using underscore as word separators. I like that! The proper name for PascalCase is TitleCase (both terms are in common parlance).

  • http://flavors.me/rkg RkG

    My idea about camelCase vs. under_score: Use camelCase for OOP related stuff (classes, methods, properties/members) and under_score for everything else, so I can quickly difference between a class property and a function local variable, f.e.

    And I also use the _ prefix for classes’ private elements (functions, properties)

  • http://www.project2manage.com/ Nate

    This was an amazing article. I really hope this gets passed around the web. Unless you are taught to code in a formal academic setting, chances are you haven’t heard of a lot of these. Most tutorials don’t cover this stuff, they just assume you already know what it means.

  • Amir

    An important note: Keep to the naming conventions of the project you work on even if you disagree with them.

    Hungarian notation is misused more often than not and best ignore. Give variables meaningful names and don’t worry about what type they are, your compiler/interperter will tell you if you’ve done something wrong and a good IDE will also help.

    The ternary operator is more than just a simple logic gate, it also returns the value of its arguments. So something like this:

    if (value>0) { return +1; }
    else
    {
    if (value<0) { return -1; }
    else
    {
    return 0;
    }
    }

    is much easier to read like this:

    return (value>0) ? 1: (value<0) ? -1 : 0;

  • Zaad

    Nice article to read :) Keep up the good work

  • Adil

    It’s excellent for coders who want quality in their work.

  • http://www.tosser.toss rachel

    Good article, although I thought the JavaScript sample suggesting that all women lie about their age and weight was offensive. Could you provide some balance in future, maybe something like:

    var Male = (function() {
    //some stereotype suggesting he is a pig or something
    });

  • http://vaporizer-store.net Michael Fever

    This makes me smile =)

  • Codemarc

    Thank you for taking the time to elegantly write down this explanation. Seeing it in ink pad, make me feel good.

  • Matt

    good post, though I disagree with your comment on hungarian notation in javascript, of course I guess its’ really a matter of personal preference but just because a variable can take on any time doesn’t mean it should. Crossing types would tend to make the code harder to understand and maintain later on, especially when its done by a different developer.

    So I guess maybe I’m implying another convention that can be useful, enforce type even when the language doesn’t. If you can’t do that then you probably need to rethink your code.

    my 2 cents.

  • http://www.chriswarbo.tk Chris Warburton

    Good idea to bring such things together, I’m sure it will be useful as I remember it taking a while to get the hang of such conventions.

    I’ve got a couple of gripes I’d like to point out:

    First is mentioned by Sam, that Hungarian notation is for semantic types that the language doesn’t support, like un/safe strings. In a loosely (I prefer “latently”) typed language then there is no type information explicitly stated in the language, thus Hungarian notation can be used to specify that. Also, whilst it’s possible to mix and match the types stored in a variable in a “loosely” typed language, that doesn’t mean it’s a good idea to do so, any more than it’s a good idea to mix and match escaped and non-escaped strings in a machine typed language (as per Sam’s example).

    The reason “foo && bar” is frowned upon as a conditional execution is because it breaks the regular programming distinction between expressions (things which have a value) and statements (instructions to carry out). Whilst imperative languages usually require instructions inside expressions, eg. sending a “getter” message to an object, this is seen as OK as long as the state doesn’t change. For example “if (a=3) foo;” is a bad idea, since it’s not only misleading to read (assignment rather than comparison), it also mangles two statements together in a way that is executed backwards (note: this would be a little better were the “if” construct acting like a function call, like “if(a=3,foo,NULL);”, or as a message send like “a <- 3 ifTrue: [foo]"). Also, by breaking the assumption that expressions don't have side effects, we make debugging a nightmare; imagine trying to debug when every assert and every printf actually changes the program's state and execution path ;)

    Also, the use of the && trick specifically is a bad idea because the skipping of the right hand side's evaluation is only done as an optimisation; an optimisation which assumes side-effect-free expressions (ie. evaluating bar has no effect on the program, thus is equivalent to not evaluating bar, and the optimisation makes sense). Thus, by using "foo && bar" instead of "if (foo) bar" what you're really saying is that you want both foo and bar to be evalutated, and their results conjoined. The fact that they're not both evaluated is just a bug in the implementation, which causes your program to have undefined behaviour. The fact that it works every time, and that the language may specify that evaluation of && chains stops when it encounters false, is no excuse for sloppy "works for me" code.

    Also, a point to note is that camelCase suffers from the problem of "toXML"/"toXml". Underscores probably have similar edge cases, but I've not come across any yet.

  • http://free-sk.t-com.hr/T800/index.html T800

    under_score sore vision

  • Etienne Dupuis

    Good relaxing read.

  • http://www.xcubelabs.com/ iPhone Development

    I was stuck with few of conventions you mentioned above.

  • http://vaguevagaries.blogspot.com Oisín

    About the example of “sName” being assigned first a string and then something else in Javascript, isn’t that a really crappy idea anyway and the type hint might encourage the developer to refactor the code not to do this?

    That said, I have more experience in statically-typed languages so maybe it’s normal and common to re-use variable names with different types… I’m learning some Lua so will probably find out soon enough. In any case, I never used Hungarian notation because it simply looked atrocious the first time I saw it in Win32 code.