[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

  1. // This variable is not available outside of the class  
  2. private $_someVariable;  
  3.   
  4. class MyClass {  
  5.    // This method is only available from within this class, or  
  6.    // any others that inherit from it.  
  7.    protected function __behindTheScenesMethod() {}  
  8. }  

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

  1. var Female = (function() {  
  2.    var _trueAge = 50,  
  3.         _trueWeight = 140;  
  4.   
  5.    return {  
  6.       age : _trueAge - 15,  
  7.       weight : _trueWeight - 30  
  8.    };  
  9. })();  
  10.   
  11. Female.age; // 35  
  12. Female.weight; // 110  
  13. 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

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

  1. var TAXRATE = .0825;  

PHP Method

  1. 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".

  1. $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:stringinteger, 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.

  1. var sName = "Lieutenant Commander Geordi La Forge";  
  2. typeof(sName); // string  
  3. ....  
  4. sName = undefined;  
  5. 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.

  1. // The dollar symbol reminds me that this variable  
  2. // has access to jQuery's various methods.  
  3. 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?

  1. $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.

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

The JavaScript World

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

  1. 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.

  1. function Person(name) {  
  2.   // If the new keyword is absent, the constructor will be the window.  
  3.   // In this case, compensate, and return a new instance  
  4.   if ( this.constructor !== Person ) {  
  5.     return new Person(name);  
  6.   }  
  7.  this.name = name;  
  8. }  
  9.   
  10. // Intentionally forgot the "new" keyword  
  11. var Joey = Person('Joey');  
  12. 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.

  1. // camelCase  
  2. var preacherOfSockChanging = 'Lieutenant Dan';  
  3.   
  4. // under_score  
  5. 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.

  1. / Project Root  
  2.   /Assets  
  3.     / js  
  4.       / min  
  5.         script_min.js  
  6.       script.js  
  7.     / css  
  8.       / min  
  9.         style_min.css  
  10.       style.css  
  11.     / img  
  12.       img1.jpg  
  13.   index.html  
  14.   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

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

Better

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

Best

  1. <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. 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.

  1. <div id="footer-wrap">  
  2.     <footer>  
  3.       My footer content goes here.  
  4.     </footer>  
  5. </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?

  1. var name = 'Joe';  
  2.   
  3. // regular  
  4. if ( name === 'Jeff' ) {  
  5.   alert("That's me");  
  6. else {  
  7.   alert("Nope");  
  8. }  
  9.   
  10. // ternary  
  11. (name === 'Jeff') ? alert("That's me") : alert("Nope"); // Nope  

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

  1. var getTweets = true;  
  2.   
  3. // regular  
  4. if ( getTweets ) {  
  5.  alert('getting them now');  
  6. }  
  7.   
  8. // Logical AND  
  9. // Right-side won't run, unless left-side is "true"  
  10. 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!

Jeffrey Way is JeffreyWay onTutsmarketplace
posted on 2010-10-31 16:57  浩然119  阅读(352)  评论(0编辑  收藏  举报