[ZZ]9 Confusing Naming Conventions for Beginners
http://net.tutsplus.com/articles/general/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
; theprivate/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 smalllightbulb 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 class
es; 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 id
s and class
es 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 themiddle-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.
id
s are less flexible, and are many times unnecessary.
8. Double Header
s and Footer
s
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.
div
s 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!