20 All Too Common Coding Pitfalls For Beginners

20 All Too Common Coding Pitfalls For Beginners

Tutorial Details
    • Difficulty: Beginner
    • Completion Time: 1 Hours

Regardless of our current skill level, we all were beginners at one point in time. Making classic beginner mistakes comes with the territory. Today, we’ve asked a variety of Nettuts+ staff authors to chime in with their list of pitfalls and solutions – in a variety of languages.

Learn from our mistakes; don’t do these things!


JavaScript Tips

1 - Unnecessary DOM Manipulation

The DOM is slow. Limiting your interaction with it will greatly increase your code’s performance. Consider the following (bad) code:

// anti-pattern
for (var i = 0; i < 100; i++){
	var li = $("<li>").html("This is list item #" + (i+1));
	$("#someUL").append(li);
}

This code actually modifies the DOM 100 times, and unnecessarily creates 100 jQuery objects. 100! A more correct approach would be to either use a document fragment, or build up a string that contains the 100 <li/> elements, and then appends that HTML to the containing element. That way, you jump into the DOM a total of once. Here’s an example:

var liststring = "";

for (var i = 100; i > 0; i--){
	liststring += "<li>This is list item #" + (99- i);
}

document.getElementById("someUL").innerHTML(liststring);

As noted above, with this technique, we touch the DOM only once, which is an improvement, but it also relies on string concatenation to build a large string. There’s a different way that we could approach this, using arrays.

var liststring = "<li>"
var lis = [];

for (var i = 100; i > 0; i--){
	lis.push("This is list item #" + (99- i));
}

liststring += lis.join("</li><li>") + "</li>";
document.getElementById("someUL").innerHTML(liststring);

When building large strings, storing each piece of the string as an item within an array element and calling join() is arguably more elegant than string concatenation. This is one of the fastest and easiest ways to build repetitive HTML in JavaScript without using a template library or framework.

2 - Inconsistent Variable & Function Names in JavaScript

This next item isn’t a performance issue, but is extremely important – especially if you are working on code that other people work on, as well. Keep your identifiers (variable and function names) consistent. Consider the following variables as an example:

var foo = "bar";
var plant = "green";
var car = "red";

It wouldn’t make sense to add another variable, called Something. This introduces inconsistency in your variable naming pattern, causing your brain to cognitively flag this variable as being different or special. This is why constants in most languages are traditionally defined with all caps.

You can take this a step further by maintaining similar length, grammatical structure, and explanatory nature when naming functions. For example, consider the following contrived function:

function subtractFive(number){
	return number - 5;
}

Naming a function that adds five to a given number should follow the same pattern, shown here:

function addFive(number){
	return number + 5;
}

Sometimes, you might name a function to indicate its return value. For instance, you might name a function that returns an HTML string getTweetHTML(). You might also prepend a function’s name with do, if the function simply performs an operation and doesn’t return a value, eg: doFetchTweets().

Constructor functions typically follow the tradition of classes in other languages, capitalizing the first letter:

function Dog(color){
	this.color = color;
}

As a general rule of thumb, you should be descriptive when naming your identifiers. Classify them together with other similar identifiers by maintaining a naming pattern that is readable and offers hints to the nature of a variable or function’s purpose.

3 - Use hasOwnProperty() in for...in Loops

JavaScript’s arrays are not associative; trying to use them as such is frowned upon by the community. Objects, on the other hand, can be treated as hash tables, and you can iterate over an object’s properties by using the for...in loop, like so:

for (var prop in someObject) { 
    alert(someObject[prop]); // alert's value of property
}

The problem, however, is that the for...in loop iterates over every enumerable property on the object’s prototype chain. This can be problematic if you only want to use the properties that exist on the actual object.

You can solve this issue by using the hasOwnProperty() method. Here’s an example:

for (var prop in someObject) {
    if (someObject.hasOwnProperty(prop)) {
        alert(someObject[prop]); // alert's value of property
    }
}

This version only alerts the values of the properties that directly reside on someObject.

4 - Comparing Boolean Values

Comparing boolean values in a condition is a waste of computation time. Take a look at the following for an example:

if (foo == true) {
    // do something for true
} else {
    // do something for false
}

Notice the condition: foo == true. The comparison of foo and true is unnecessary because foo is already a boolean value (or it’s a truthy or falsey one). Instead of comparing foo, simply use it as the condition, like this:

if (foo) {
    // do something for true
} else {
    // do something for false
}

To test for false, use the logical NOT operator, as shown below:

if (!foo) {
    // do something if foo is false
} else {
    // do something if foo is true
}

5 - Event Binding

Events are a complicated subject in JavaScript. Gone are the days of inline onclick event handlers (except in some very rare “splash page” cases). Instead, use event bubbling and delegation.

Let’s imagine that you have a grid of pictures that need to launch a modal lightbox window. Here’s what you shouldn’t do. Note: we’re using jQuery here, assuming you are using a similar library. If not, the same bubbling principles also apply to vanilla JavaScript.

The relevant HTML:

<div id="grid-container">
	<a href="someimage.jpg"><img src="someimage-thumb.jpg"></a>
	<a href="someimage.jpg"><img src="someimage-thumb.jpg"></a>
	<a href="someimage.jpg"><img src="someimage-thumb.jpg"></a>
	...
</div>

The (bad) JavaScript:

$('a').on('click', function() {
	callLightbox(this);
});

This code assumes that calling the lightbox involves passing an anchor element that references the full size image. Instead of binding to each anchor element, bind to the #grid-container element instead.

$("#grid-container").on("click", "a", function(event) {
	callLightbox(event.target);
});

In this code, both this and event.target refer to the anchor element. You can use this same technique with any parent element. Just make sure to define the element that should be the event’s target.

6 - Avoid Ternary Redundancy

The overuse of ternary statements is quite common both in JavaScript and PHP.

// javascript
return foo.toString() !== "" ? true : false;
// php
return (something()) ? true : false;

A condition expression always returns a true or false value, meaning you don’t need to explicitly add true/false as ternary values. Instead, you could simply return the condition:

// javascript
return foo.toString() !== "";
// php
return something();

PHP Tips

7 - Use Ternary When Appropriate

if...else statements are a central part of most languages. But doing something simple, such as assigning a value to a variable based upon a condition – well, they can junk up your code. Consider the following code:

if ($greeting) 
{
    $post->message = 'Hello';
} 
else 
{
    $post->message = 'Goodbye';
}

This code can be reduced to one line, while still maintaining readability by using the ternary operator, like this:

$post->message = $greeting ? 'Hello' : 'Goodbye';

It’s clear, concise, and gives you the functionality you need.

As useful as the ternary operator is, the most important guideline is not to over-use it! The goal of coding is not to cramp your logic into as few lines as possible.

8 - Throw Exceptions Instead of Inception-Style Nesting

Let’s face it: many levels of nesting is ugly and difficult to maintain/read. The following code is a relatively simplified example, but they get much worse over time:

// anti-pattern
$error_message = null;

if ($this->form_validation->run())
{
	if ($this->upload->do_upload())
	{
		$image = $this->upload->get_info();

		if ( ! $this->image->create_thumbnail($image['file_name'], 300, 150))
		{
			$error_message = 'There was an error creating the thumbnail.';
		}
	}
	else
	{
		$error_message = 'There was an error uploading the image.';
	}
}
else
{
	$error_message = $this->form_validation->error_string();
}

// Show error messages
if ($error_message !== null)
{
	$this->load->view('form', array(
		'error' => $error_message,
	));
}

// Save the page
else
{
	$some_data['image'] = $image['file_name'];

	$this->some_model->save($some_data);
}

That’s some nasty code, but you can make it drastically cleaner by using exceptions, like so:

try
{
	if ( ! $this->form_validation->run())
	{
		throw new Exception($this->form_validation->error_string());
	}

	if ( ! $this->upload->do_upload())
	{
		throw new Exception('There was an error uploading the image.');
	}

	$image = $this->upload->get_info();

	if ( ! $this->image->create_thumbnail($image['file_name'], 300, 150))
	{
		throw new Exception('There was an error creating the thumbnail.');
	}
}

// Show error messages
catch (Exception $e)
{
	$this->load->view('form', array(
		'error' => $e->getMessage(),
	));

	// Stop method execution with return, or use exit
	return;
}

// Got this far, must not have any trouble
$some_data['image'] = $image['file_name'];

$this->some_model->save($some_data);

It might be the same number of lines, but it allows for considerably more readable and maintainable code. It also avoids those difficult debugging sessions, where you’ve missed a possible path through the if statement. Keep it simple!

Second Opinion: be very, very careful, when using exceptions for flow control. Refer here for additional information.

9 - False-Happy Methods

Being exception-happy is far more advantageous than being false-happy.

Ruby or Python developers are used to watching for trivial exceptions. While that sound tedious, it’s actually quite a good thing. If anything goes wrong, an exception is thrown, and you instantly know where the problem is.

In PHP – and especially when using older frameworks, such as CodeIgniter – you get what I refer to as “false-happy code” (as opposed to exception-happy). Instead of having an exception get all up in your face, it just returns a false value and assigns the error string to some other property. This forces you to fish it out of the class using a get_error(); method.

Being exception-happy is far more advantageous than being false-happy. If an error occurs within your code (eg: could not connect to S3 to upload an image, or a value is empty, etc.), then throw an exception. You can also throw specific types of exceptions by extending the Exception class, like so:

class CustomException extends Exception {}

Throwing a custom exception makes debugging considerably easier.

Tip 10 - Use Guard Clauses

It’s common to use if statements to control a function or method’s execution path. It’s tempting to test a condition and execute a lot of code when the condition results in true, only to simply return in the else statement. For example:

function someFunction($param) {
    if ($param == 'OK') {
       $this->doSomething();
       return true;
    } else {
       return false;
    }
}

This kind of solution, however, represents a potential for spaghetti code. You can make this code easier to read by reversing the condition. Here’s the better version:

function someFunction($param) {
    if ($param != 'OK') return false;

    $this->doSomething();
    return true;
}

Isn’t that easier to read? It’s a simple change that makes a drastic difference in the readability of your code.

Tip 11 – Use while for Simple Iterations

The for loop is commonly used when you need, for example, a counter. Here’s a simple for loop:

for (var i = 0; i < x; i++) { 
    ... 
}

There are some very good reasons to use a for loop, but a while loop may be better if you just need something simple, like this:

var i = x;

while (i--) { 
    ... 
}

It doesn’t work in every situation, but it is an alternative.

Tip 12 – Keep Methods Maintainable

This is easily one of the most frequent mistakes made by newcomers.

A method is an object’s unit of work, and limiting your methods to a maintainable size makes your code easier to read and maintain. Take a look at the following monster method:

class SomeClass {

	function monsterMethod() {
		if($weArePilots) {
			$this->goAndDressUp();
			$this->washYourTeeth();
			$this->cleanYourWeapon();
			$this->takeYourHelmet();
			if($this->helmetDoesNotFit())
				$this->takeAHat();
			else
				$this->installHelmet();
			$this->chekcYourKnife();
			if($this->myAirplain() == "F22")
				$this->goToArmyAirport();
			else
				$this->goToCivilianAirport();
			$this->aim();
			$this->prepare();
			$this->fire();
		}
	}

}

Consider breaking this monster method into smaller, descriptive chunks, each being responsible for performing one well-abstracted action. This is easily one of the most frequent mistakes made by newcomers.

class SomeClass {

	function monsterMethod() {
		if($weArePilots) {
			$this->prepareYourself();
			$this->tryHelmet();
			$this->findYourAirport();
			$this->fightEnemy();
		}
	}

	private function prepareYourself() {
		$this->goAndDressUp();
		$this->washYourTeeth();
		$this->cleanYourWeapon();
		$this->chekcYourKnife();
	}

	private function tryHelmet() {
		$this->takeYourHelmet();
		if($this->helmetDoesNotFit())
			$this->takeAHat();
		else
			$this->installHelmet();
	}

	private function findYourAirport() {
		if($this->myAirplain() == "F22")
			$this->goToArmyAirport();
		else
			$this->goToCivilianAirport();
	}

	private function fightEnemy() {
		$this->aim();
		$this->prepare();
		$this->fire();
	}

}

There we go: cleaner, and easier to debug!

Step 13 - Avoid Deep Nesting

Too many levels of nesting makes code difficult to read and maintain. Consider the following:

function doSomething() {
    if ($someCondition) {
        if ($someOtherCondition) {
            if ($yetSomeOtherCondition) {
                doSomethingSpecial();
            }

            doSomethingElse();
        }
    }
}

You can refer to Tip #10 to make this code easier to read by reversing some of the conditions.

function doSomething() {
    if (!$someCondition) {
        return false;
    }

    if (!$someOtherCondition) {
        return false; 
    }

    if ($yetSomeOtherCondition) {
        doSomethingSpecial();
    }

    doSomethingElse();
}

This code is considerably cleaner and produces the same results as before.

When you find yourself with nested if statements, closely examine your code; your method may be performing more than one task. Here’s an example:

function someFunc() {
	if($oneThing) {
		$this->doSomething();
		if($anotherThing)
			$this->doSomethingElse();
	}
}

In these cases, extract the nested methods into their own method:

function someFunc() {
	if($oneThing) {
		$this->doSomething();
		$this->doAnotherThing($anotherThing);
	}
}

private doAnotherThing($anotherThing) {
	if($anotherThing)
		$this->doSomethingElse();
}

Tip 14 – Avoid Magic Numbers and Strings

Magic numbers and strings are evil. Define variables or constants with the values you want to use in your code.

Instead of this:

function someFunct() {
	$this->order->set(23);
	$this->order->addProduct('superComputer');
	$this->shoppingList->add('superComputer');
}

Specify what those numbers and strings mean, and assign them to a variable with a meaningful name, like this:

function someFunct() {
	$orderId = 23;
	$selectedProductName = 'superComputer';

	$this->order->set($orderId);
	$this->order->addProduct($selectedProductName);
	$this->shoppingList->add($selectedProductName);
}

While some might argue that we’re needlessly creating variables, the performance hit is negligible. Readability always takes priority. Remember: don’t optimize for performance until you can describe why it’s necessary.

Step 15 - Use Built-In Array Functions

Use the built-in array functions instead of foreach().

Not Ideal:

foreach (&$myArray as $key =>$element) {
   if ($element > 5) unset ($myArray[$key]);
}

Better:

$myArray = array_filter($myArray, function ($element) { return $element <= 5;});

PHP offers a variety of array methods. They’re confusing at first, but take a day and try to learn as many as possible.

Tip 16 - Don’t Overuse Variables

It’s easy to overuse variables, but remember that variables are stored in memory. For every variable you create, the system needs to allocate memory for that variable. Look at this code:

public function get_posts() {
	$query = $this->db->get('posts');
	$result = $query->result();
	return $result;
}

The $result variable isn’t necessary. The following code omits that variable:

public function get_posts() {
	$query = $this->db->get('posts');
	return $query->result();
}

The difference is subtle, but we were able to improve this simple example. We kept the $query variable because it relates to the database, while $result related more to our logic.


General Programming Recommendations

Tip 17 - Rely on the Database Engine

Anything less is a code smell.

A database is designed for working with data; use its tools and abilities to make your application more efficient.

For example, you can avoid redundant database queries in many circumstances. Most plug-and-play user management scripts use two queries for user registration: one to check whether the e-mail/username already exists and another to actually add it to the database. A much better approach is to set the username field to UNIQUE. You can then use native MySQL functions to check whether or not the record was added to the database.

Tip 18: Properly Name Your Variables

The days of naming your variables x, y, z are over (unless, of course, you’re dealing with a coordinate system). A variable represents an important part of your logic. Don’t want to type a long name? Get a better IDE. Modern IDEs auto-complete variable names in a blink of an eye.

Always be coding for six months from now. Are you certain that you’ll remember what that $sut variables refers to a year from now? Likely not: be descriptive. Anything less is a code smell.

Tip 19 - Methods Represent Actions

Mistakes happen; the key is to learn from them.

Name your methods with verbs representing the action they perform. The main concept is the exact opposite of the variable naming scheme. Use a short, but descriptive, name in a large scope (ie: public methods), and use a longer and more detailed name in a short scope (ie: private / protected methods). This helps make your code read like well written prose.

Also avoid any language other than English, when naming your methods. It’s annoying to read function names like 做些什麼() or делатьчтото() in your project. It may be impossible for other programmers to understand your intent. While it might seem arrogant, for better or worse, English is the adopted language of code. Try to use it, if we’re working on a large team.

Tip 20: Structure Recommendations

Finally, code structure is just as important to readability and maintainability as anything else we’ve talked about today. Here are two recommendations:

  • Indent with four or two space-width tabs. Anything more, such as eight spaces, is too much and will make your code difficult to read.
  • Set a reasonable line-width and respect it. Forty characters in a line? We’re not in the ’70s any more; set your limit to 120 characters, put a mark on the screen, and force yourself or your IDE to respect that limit. 120 characters gives you a nice width without making you scroll.

Conclusion

“I’ve never made a stupid programming mistake.” — No one, ever.

Mistakes happen; the key is to learn from them. We at Nettuts+ have made, and will continue to make, mistakes. Our hope is that you learn from our mistakes so that you can avoid them in the future. But, to be honest, the best way to learn best practices is to make the mistakes yourself!

Thanks for reading!

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

    I enjoyed that – will send it to the junior developer in our company to taese him :)

  • http://ashleyclarke.me/ Ashley Clarke

    Nice article :)

  • http://twitter.com/tomasdev Tom Roggero

    You are missusing the word “beginner” and also there are a bunch of your “tips” that are worse in performance terms.

    • Ian

      Tom, please specifically point those out so newbies will know :-)

      • Denis

        #1: String concatenation is faster than array joining: http://jsperf.com/string-concat-vs-array-join-10000/3.

      • kinophotography

        Array.push() isn’t the most optimised. That test should also include my array[I] = blah…

      • Denis

        I’ve tried it, .push is faster than accessing by index: http://jsperf.com/array-push-v-array-index

      • http://twitter.com/jeffrey_way Jeffrey Way

        That entirely depends on the browser. The performance differences either way are negligible.

      • Denis

        Well, sure. I would never mention performance in this case, but please note that the original post claims that array joining is faster, which is both irrelevant and incorrect.

        Quoting the original article:

        “When building large strings, storing each piece of the string as an item within an array element and calling join() is more efficient than string concatenation”

      • http://twitter.com/jeffrey_way Jeffrey Way

        Fixed.

      • Ricardo RCDMK Souza
      • http://twitter.com/tomasdev Tom Roggero

        Hi Ian

        Do you expect at all for a beginner to know about: event binding, ternary operator, handling of classes, handling of exceptions, databases engines?

        As a SemiSenior Developer, I need to disagree. About the performance tips, is just a matter of fact about putting in JsPerf all that you say and comparing both cases. One example is comparing `if (something === true)` is cheaper than `if (something)`

  • Jed

    Some good tips in here and some not so good.

    #3 typo: getOwnProperty() should be hasOwnProperty()

    #4: It’s true that it can be convenient to take advantage of JavaScript’s truthiness/falsiness, but you don’t really save much by doing so, and it’s actually much better advice to do strict comparisons: if ( foo === true ) …

    #10/13: It’s generally much better form to have one or two exit points from a function/method, rather than a bunch of return statements sprinkled throughout.

    • http://twitter.com/jeffrey_way Jeffrey Way

      Hey, Jed –

      #3. Fixed.

      #4. Ehh, I suppose it comes down to preference. I much prefer the implied truthiness/falsiness, but don’t see anything wrong with being explicit.

      • http://franticlabs.com/ David D’hont

        By default PHP returns false anyway, so True or False doesn’t matter. If the IF statement ran correctly; then you will have your result. If you aren’t going to return anything other then False during the else statement. Well then there’s no point in doing that ELSE statement at all.

        Also, I get where you are coming from, PHP isn’t compiled. So the code is all executed either way. And as this article implied itself #16, every piece of code you add is memory. Therefor, less code is more optimized.

        The way I see it, it’s unnecessary code. Now don’t get me wrong. I’m not saying you can’t use your preference. But that doesn’t necessarily mean it’s a “pitfall for beginners”.

  • http://www.facebook.com/profile.php?id=635878549 Songpol Sripao-eiam

    Nice article for beginner and me :)

  • Denis

    #1: String concatenation is faster than joining Aray.

    #1: Creating intermediate jQuery objects leads to more maintainable code at a tiny performance loss. (Of course, as long as elements are detached from DOM).

    #3: An even better suggestion would be to use $.each (or _.each or similar).

    #5: Reasoning is very weird. What assumes what? Main reasons are performance and automatic support of mutated DOM.

    #6: In PHP example it’s absolutely not clear that something() returns a boolean. Use typecasting: (bool) something();

    #8: As you mention later on, custom exceptions. For different situations use different exceptions subclassing one main exception, so that code down the line could catch only particular situations it wants to catch.

    #9: What is get_error? O_o

    • http://www.facebook.com/madealive Ben Martin

      Thought typecasting is better in my opinion, you can also use return something() == true;

      • Alan

        I think you should use three equals (===) in PHP when comparing booleans, some strings and ints will equate to false IIRC

      • JeremyMcPeak

        Renaming something() to isSomething() or is_something() is much clearer, imo.

  • http://www.facebook.com/joaocunhaoficial João Cunha

    For Tip #13, there is another approach which is great as well. Consider a form validation routine:

    var isValid = true;
    isValid = isValid && (name.length <= 50);
    isValid = isValid && aRegexFuncion(value, /^[A-Z]{2}d{9}[A-Z]{2}$/i);

    … and so on.

    Then all you need to do is to check if isValid is, in fact, valid :)

    • http://www.facebook.com/madealive Ben Martin

      This is a great practice that has greatly increased the readability and maintainability of my code.

  • Mano

    why is the reference operator in foreach array?

    • Patkos Csaba
      Author

      If you refer to #15, the reference operator allows you to modify the original array you are passing into foreach().

      • dazweeja

        Actually it’s not even valid PHP code in that context.

  • zvineyard

    When using ternary operators, you want to make sure you put the operations in parentheses, otherwise you could get wonky output. So, instead of:

    $post->message = $greeting ? ‘Hello’ : ‘Goodbye’;

    use

    $post->message = ($greeting ? ‘Hello’ : ‘Goodbye’);

    • Denis

      “Wonky output”? What? If the expression is more complicated, explicitly ordering operators is good.
      But why would you add them around a single expression? Is this also how you write:

      $foo = (something($bar));
      $quux = (2 + 3);

      And then, why stop there?

      $post->message = (($greeting) ? (‘Hello’) : (‘Goodbye’))

      Sorry about the teasing tone. :)

      • zvineyard

        When using ternary expressions, adding parentheses round a single expression is still a good idea because, when used in concatenation, math(bit-wise/logical) expressions like a ternary expressions (condition ? true : false) will lose precedence and be interpreted with unexpected results. It isn’t required. It could just save you from introducing a bug later.

      • Denis

        Ah, well, in concatenation – sure, you’re right. I was referring to your previous example with variable assignment. I think using grouping there is not helpful in any way, other than maybe growing a habit.

  • xwlee

    great tips, thanks a lot

  • Rakesh

    nice one..thanks

  • jack

    Some pretty bad tips if you ask me, and you violate your own rules-

    You use False-Happy Methods in #10 and #13, and #16 and #14 are opposite- use variables and don’t use variables.

    • http://franticlabs.com/ David D’hont

      I could not have put it better. This article is all kinds of wrong and the quality of this particular blog has been going downhill for a while.

      • rtpHarry

        Yep, and while it might not be true for interpreted languages, I have read before that compiled languages optimise away those intermediate variables anyway.

  • taylorhutchison

    One all too common pitfall for tutorial writers.
    1) Using terms like “hash table” without defining it when speaking to beginners.

    • http://twitter.com/freatbeater Mohammad Gufran

      One all too common pitfall for newbies:
      Diverting from topic for a definition they can easily find over google or wikipedia, along with a ton of links to articles explaining the definition in a cool way.

      Kick me if I am wrong!

      • http://franticlabs.com/ David D’hont

        I hate this mentality of people saying “just google it”. If you are going to explain something then you fucking do it right. Not this “google it” shit.

        If the articles were for us that actually do google it, then they wouldn’t have to make them now do they?

      • http://twitter.com/freatbeater Mohammad Gufran

        well, let me be clear with my words, I said:

        “Diverting from topic for a definition they can easily find over google or wikipedia, along with a ton of links to articles explaining the definition in a cool way.”

        the topic of this article is “Common coding pitfalls for beginners” not “Understanding the ‘hash table’”. This article is explaining pretty much everything relevant to the topic, for any other explanation that is totally irrelevant you are free to use your common sense and find out more about it over google if you are really interested in it. That is how we learn in 21st century, not by posting like “Hey, you havnt even explained what is a class and you used the term in your article ? if you are going to write an article then you f**king write it down to the details about every word you used in here, I hate this ‘google it’ shit, I am not going to search anything over google so you better re-write the article.”. Really ?

      • http://franticlabs.com/ David D’hont

        1. I never said they had to re-write the article.
        2. I never said that I wouldn’t Google it.
        3. I never said they had to explain everything in full detail.

        An to be clear, maybe you don’t fully understand what I meant.

        If you write an article, you shouldn’t assume that your users are going to Google it.
        And if people ask you a question about it, don’t tell them to Google it if you know the answer.

        I have seen it far too many times, don’t have 5 minutes to explain, but has 5 to tell them to google it?

      • http://profiles.google.com/florin.jurcovici Florin Jurcovici

        If you write an article, you write it for a specific audience. In this case, the audience is programmers. Beginners, but still programmers. They should know what a hash table is. If they don’t, they should google it – it’s basic knowledge of data structures, and data structures and algorithms are (or should be) basic knowledge for any programmer.

        I think the huge demand for programmers coupled with the limited offer has lowered the bar for professional qualifications in our profession to a point too low.

      • http://twitter.com/freatbeater Mohammad Gufran

        Like Florin Jurcovici said, ‘When you write an article, you write it for specific audience.’

        and every time you know that for being a part of that ‘Audience’ pool one have to qualify some basic requirements, both in knowledge and in skills.

        First thing, when you call yourself a newbie programmer anyone would assume that you have passed the the “Hello world” kind of programming level and your skills are above the base line of requirements.

        As long as the debate is about ‘Hash table’, I’d say its the most basic term every (beginner) programmer should be familiar of, as much basic as tags in PHP, Import in Python, #include in C and C++ and class in JAVA, because this is not a feature in any language but the concept that is used in every language.

        of course I knew the answer for “taylorhutchison’s” doubt but I still want him to look over google because the question itself contains a lot of doubts and other questions in it, the way he asked the question tells very clear that the term and concept is entirely new to him. So the best way for him to go from scratch to enough is google and wiki, or maybe some book that I am not aware of ?

        and yeah, when you ignore a wealth of knowledge and pick a ridiculous word out of an article to start another world war, you actually want to say:

        1. I’ll never google it
        2. You have to explain everything in full detail
        3. Go, rewrite the entire article

      • Matt

        I agree that the answer to all your questions shouldn’t just be to “Google It”, I certainly feel that people should be given some level of credit that they don’t need basic concepts like hash tables explained to them or at least be capable of researching what it is (Google or otherwise). Although this article is intended for newer programmers the basic concepts covered in this article is good advice for everyone, new or old.

      • http://franticlabs.com/ David D’hont

        I beg to differ. Oh and also: don’t assume things about your users.

      • http://www.webmaster-source.com redwall_hp

        It seems like the perfect opportunity for an aside. Take it out of the main content, but make it clearly visible. (The For Dummies books are really good about this, putting ancillary definitions or warnings in breakout boxes.) If the Tuts+ stylesheet doesn’t have a little floated box styling for elements in the content, they’re missing out on a good opportunity.

      • Jason P Sage

        No need to get nasty because you disagree… geesh

      • taylorhutchison

        If the author does not want to divert attention away from his main goal to address topics such as hash tables then the author should identify concepts that need additional explanation (something a beginner would not understand) and provide specific links. Don’t just assume that people will “google it” to the right answer. Its not just about providing a link to a definition or wikipedia article. Its about providing a resource that teaches the topic. It could be the difference between an A tutorial and an A+ tutorial.

        I think this tutorial was fantastic, but since I have experience making screencasts and tutorials I wanted to express my opinion that putting forward concepts without providing meaning or giving context is very confusing for beginners.

    • http://profiles.google.com/florin.jurcovici Florin Jurcovici

      Someone calling himself a beginner programmer and not knowing what a hash table is should actually be fired.

      • WhazGoogle

        Hash tables are now legal in Colorado and Washington. I still don’t see the relevance.

      • http://www.blackbookoperations.com/ Black Book Operations

        # to that!

      • Awesome

        Not really, I didn’t know what a hash table was.

        I had to Google it just to classify it as the same thing as an associative array. (Correct me if I’m wrong)

        It’s kinda like saying a C programmer should know what terms delegate mean, or that a C# programmer should should know what a callback function is.

      • http://profiles.google.com/florin.jurcovici Florin Jurcovici

        Hash tables are just one way of implementing associative arrays.

        You have the type HashTable in C#, and have the types HashMap in C++ and Java. You may not have implemented a hash table yourself, but you should have an understanding of how it works, if you want to be able to choose the right map implementation depending on your use case.

        You do have the notion of a callback used already since 16 bit Windows for Windows programming, and it’s a common concept in web programming. In fact, callbacks are an essential mechanism used in languages as old as C++ or Lisp. Callbacks should be a concept familiar to anybody having used any mainstream programming language except Java.

        I don’t know your background, but I’d definitely feel hurt if I had to work with a programmer not knowing what a hash table or a callback is. Or understanding the concept of a delegate. All three of these concepts are well known since decades ago, maybe under different names at different points in time. It may happen that companies put new labels on it, and that you need to google the names, but you should definitely have an understanding of how they work, if you want to call yourself a programmer.

      • http://www.kksmith.me/ K.K.Smith

        I thought a “hash table” was that little table beside the sofa in your living room where you…

        .. nevermind.

  • Ahmad Shukr

    Thanks for information,but:
    document.getElementById(“someUL”).innerHTML(liststring);
    should be
    document.getElementById(“someUL”).innerHTML=liststring;

  • Patkos Csaba
    Author

    Here are my opinions on what was discussed so far. I am just one of the many author who put together this list, and this is just my personal opinion.

    When it comes to code structure I would forget performance. Performance tuning is usually the opposite of refactoring and clean code. Because many of you are pointing out performance issues I consider you shouldn’t care about them until proven a real problem. Knowing that your code is not the fastest and greatest and consciously writing code that other people can better and easier understand is the greatest care you can give to your source code. When you do so, and your application __is proven__ to not be fast enough, than you can go to those places and __sacrifice readability__ for speed. But I alway recommend to write your code so that other people can understand it, and you will see that speed optimizations are required only rarely and you will do them when needed and avoid premature optimization. Also an approach like this can shed light on the real performance issues you may have instead of what problems you __think__ you have.

    I know that in the article there are a few tips referring to speed optimizations, #1 for example, but I also think these are the obvious stuff, things that you can actually observe while running the code on your own computer you being the only user. The speed difference between a string concatenations or an array join? I bet you can’t spot that unless you have exceptionally large number of elements, which may be a proven case of need for performance optimization. But how many projects will need it?

    • Denis

      You are 100% correct. But why the hell does the original article itself mention performance reasons to use array joining over string concatenation? That is what’s wrong with the article, not the particular choice.

      Quoting the original article:

      “When building large strings, storing each piece of the string as an item within an array element and calling join() is more efficient than string concatenation”

      • Patkos Csaba
        Author

        Ah, got it. I don’t know…

      • http://twitter.com/jeffrey_way Jeffrey Way

        Fixed.

    • MPinteractiv

      ” Because many of you are pointing out performance issues I consider you shouldn’t care about them until proven a real problem. ”
      I disagree , especially with javascript where perfomances are critical on mobile. I’d take performance over “maintainability” anytime.

      • http://profiles.google.com/florin.jurcovici Florin Jurcovici

        Performance and maintainability are orthogonal most of the time. Maintainable code is usually small code, and small code is usually fast. A smart JS engine will optimize your code execution better than you will ever be able to, and built-in functions will always be faster than your alternative JS implementation. It’s usually bad architecture which makes JS code slow – for example, using long switch statements instead of polymorphism in loops is a typical pattern for bad performance. Beginners, by not consistently sticking to good coding principles, are more likely to introduce such a problem without even being aware of it – instead of using polymorphism, a class uses a long switch statement in a function, which gets from a loop located in another function.

    • http://profiles.google.com/florin.jurcovici Florin Jurcovici

      Premature optimization is the root of all evil — Donald Knuth. But maybe the beginners commenting here have never heard of Donald Knuth.

  • VKumar

    #4 : Putting explicit foo==true makes code more readable particularly when it comes to maintenance of the application and if the methods are big with multiple condition.

    If(foo== true && bar == false && x==y)

    or

    if( foo && !bar && x==y)

    Which one reads better ?

    • Benjamin Millagou

      The second, obviously.

    • http://profiles.google.com/florin.jurcovici Florin Jurcovici

      Putting explicit == true/false makes the code more readable for people used to that idiom. Think natural language: does “if (it rains outside == true) take the umbrella” make more sense than ” if it rains outside, take the umbrella”?

  • aaronmhill

    It says “20 coding pitfalls” yet each of the list items were “tips”. Shouldn’t the title be “20 tips to avoid common pitfalls” or the individual titles of the tips be re-phrased to describe the sub-par behavior? (the titles of 1, 2, and 9 all describe “pitfalls”, the other titles describe “tips”)

    Also — some of the items (10, 11, 12, 14, 15, 17, 18, 19, 20) use “Tips” as a prefix, two (13, 15) use “Step”, and the first 9 use no prefix at all. This is very inconsistent and confusing.

  • shamim

    Nice tutorials and tools..
    Thanks to share…

  • hasan

    This is really a great collection..
    Thanks to share..

  • http://dsheiko.com Dmitry Sheiko

    Step 13 – Avoid Deep Nesting
    I would refer to corresponding patterns: strategy, chain of responsibility

  • Panta

    #16 is the only advice I disagree with completely.

    Compiler/interpreter will usually optimize away the needless variable(s) in production, but during testing, you’ll be able to set a breakpoint on the extra line and see the result before returning it.

    Of course, this behavior might depend on the IDE / editor, but in my experience, almost all are picky about this particular issue.

  • http://www.facebook.com/chris.schudoma Chris Schudoma

    Nice post, but pilots usually fly a “plane” not a “plain” (Tip 12) ;P

  • Spencer

    #8 Oh my. Did you just suggest to a beginning programmer that instead of nesting if statements that they should instead use Exceptions as flow control and then resolve it using pokemon exception handling? That is so incredibly wrong. Are you being ironic?

    Dont use exceptions for flow control:
    http://c2.com/cgi/wiki?DontUseExceptionsForFlowControl
    http://blog.seanja.com/2010/04/exceptions-are-not-for-flow-control/
    http://ciaweb.net/pear-exception-use-guidelines.html#toc26

    • bob sacamano

      thank you – i was going to post exactly the same thing. don’t use exceptions for flow control. bad bad bad.

  • Bounasser Abdelwahab

    innerHTML is a property not a method

  • speedbump1981

    Hey, thanks! I actually used one of those tips to fix a mistake I made in my JQuery!

  • Uncle Fred

    Boy, that escalated quickly

  • sv

    #1: Building html from dynamic data using string concatenation or array joining is a huge beginners mistake because it fails to take into account the necessary escaping, which can in the simple case leave you with badly formatted or missing data, and in the more complex case leave you wide open to injection attacks.

  • http://www.facebook.com/madealive Ben Martin

    In #4, it should be noted that == (equality operator) and === (strict equality operator) function differently.
    if(foo){ ... } functions exactly the same as if(foo == true){ ... }, but it is not the same as if (foo === true){ ... }

    Likewise,
    if(!foo){ ... } functions exactly the same as if(foo == false){ ... }, but it is not the same as if (foo === false){ ... }

    There can be times, although few, where the strict equality operators are needed to compare strictly against true/false. These cases occur more in PHP than in Javascript, such as in array_search (http://www.php.net/manual/en/function.array-search.php)

  • Jason P Sage

    Readability does not trump speed of execution. Make fast code that’s readable.

    • http://twitter.com/jeffrey_way Jeffrey Way

      I’d say, unless you’re visibly seeing the effects of a performance hit, then readability is more important — especially for little things that don’t make much difference either way.

  • Jason McCreary

    Excellent article. Especially the tips about clear code. I’ve started a series of articles in hopes to better PHP developers – http://jason.pureconcepts.net/2012/08/better-php-developer/

  • Hossein Zolfi

    First thanks for your great explaination, I really enjoy it

    As you mention at #13, I really like to know your idead about this refactoring.

    #8
    function validateForm()
    {
    –if (!$this->form_validation->run())
    –{
    —-return $this->form_validation->error_string();
    –}

    –if (!$this->upload->do_upload())
    –{
    —-return ‘There was an error uploading the image.’;
    –}

    –$image = $this->upload->get_info();
    –if ( ! $this->image->create_thumbnail($image['file_name'], 300, 150))
    –{
    —- return ‘There was an error creating the thumbnail.’;
    –}

    –return “”;
    }

    {
    –// Show error messages
    –$error_message = $this->validateForm();
    –if ($error_message !== null)
    –{
    —-$this->load->view(‘form’, array(
    ——–’error’ => $error_message,
    —-));

    —-return ;
    –}

    –// Save the page
    –$some_data['image'] = $image['file_name'];
    –$this->some_model->save($some_data);
    }

  • Linish

    Good Article

  • andrei

    i don’t really like that there’s no argument for #15. readability? performance? author’s personal preference?

  • Alan

    I’m not sure if it’s a US / UK thing or not, but in the monstermethod I think the myAirplain() property should be called myAirplane(). Nit picking aside, I liked this – reminds me of some silly things I did (and some that I still am doing)

  • Octavian Damiean

    So #4 is actually quite wrong.

    You obviously forgot that JavaScript is a loosely typed language which means that the variable you are expecting to be of type bool can become something completely different, either by accident or on purpose.

    The checks you perform on #4 are not for true and false they are for truthy and falsy. Here is a short example if what that means[1].

    I’d even propose to not only check for equality (==) but also for identity (===) if you expect a certain type.

    [1]: http://jsbin.com/ujuzap/3/

  • http://twitter.com/netsi1964 netsi1964

    Hi,

    Great post! Thank you!

    #3: It seems that the tip about “hasOwnProperty” is not correct. It will still return true if the property of the object is a function. See my test here on jsfiddle: http://jsfiddle.net/netsi1964/v7MRV/

    I will continue to test using typeof!===’function’.
    /Sten

  • Djr587

    Great read, however using echo versus print in PHP is significantly improved and accepts multiple values therefore cutting down on processing time. Print used as apropos when needed.

  • Bilal

    Nice article. There will always be disagreements but overall this article is insightful and helpful.
    Thanks for it.

  • Harry

    For javascript suggestion 1, unnecessary DOM manipulation, developers should be cautious because it is possible to reach the maximum allowable length of a string on mobile platforms. If this happens you will get a string equal to null and at least in my case zero informative log messages.

  • kenn

    From this:

    function doSomething() {
    if (!$someCondition) {
    return false;
    }
    if (!$someOtherCondition) {
    return false;
    }
    if ($yetSomeOtherCondition) {
    doSomethingSpecial();
    }
    doSomethingElse();
    }

    To this

    function doSomething() {
    if (!$someCondition || !$someOtherCondition) {
    return false;
    }
    if ($yetSomeOtherCondition) {
    doSomethingSpecial();
    }
    doSomethingElse();
    }

    I guess?

  • Crazhou

    very nice

  • Fratyr

    So much bullsh*t between tip 14 and 16. :)
    Such a contradiction :)