Book review: The art of SEO

•February 18, 2013 • Leave a Comment

[Disclaimer: I’ve received a free copy of this book for reviewing]

In these last couple of days, I’ve spent most of my free time reading this book. It’s a really thick book (I must confess that is was way more thicker than I was expecting initially). It does cover a lot of ground and it’s probably the best reference on the subject available on print. It’s a little dense and I wouldn’t recommend it to someone who is just starting doing web development. Even though it covers several topics in depth, I must say that chapter 7 is really a must for anyone interested in understanding how links are used for ranking pages.

Even though the book has lots of examples (I think it would be better to reduce them, specially the ones presented in the first chapters), this isn’t a platform specific book. In other words, don’t expect to get instructions on how to perform a specific task for server A or platform B. Instead, expect to find lots of examples that can be used across all platforms. Overall, I liked the book and that’s why I’m giving it an 8/10.

The–LiteralPath parameter

•February 15, 2013 • Leave a Comment

It’s 2013, we’ve got Powershell for a couple of years now, so it’s only natural to automate things, right? At least, that’s what I try to do. So, one of the things I’ve ended up doing some time ago was writing a simple script for copying files from an USB pen to a specific folder. As you can see, it’s really simple:

ls j:\ | foreach { 
  $itemName = $_.Name.Replace('.', ' ') 
  $destination = ls | where { $itemName -match $_.Name } | select -First 1 
  if( $destination -ne $null){       
   mi $_.PSPath $destination.PSPath -Verbose -WhatIf  
  } 
}

After some time where everything seemed to be running ok, I’ve noticed that some of the files weren’t being copied. After further analysis, I’ve noted that files contained the [ and ] chars weren’t being copied. Fortunately, we have StackOverflow and I’ve ended posting my question over there. One of the answers suggested to use the –LiteralPath parameter for the move-item cmdlet. According to the docs, the –LiteralPath parameter :

Specifies the path to the current location of the items. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Did you notice the wildcards part? Yep, wildcards…unfortunately form me, I had completely forgotten that [] define wildcards which match a range of characters (note to self: do read the PowerShell docs). For instance, and this is just copied from the docs, here’s a quick example:

[a-l]ook matches book, cook or look, but not took.

Aha! ok, now it makes sense…that’s why those files which contained the [ ] on its name weren’t being copied. PowerShell was translating the values defined within [ ]  into ranges. Another note to self: don’t forget about wildcards when you’re writing PowerShell scripts.

And that’s it for now. Stay tuned for more.

Updated material for ASP.NET MVC book

•February 14, 2013 • Leave a Comment

If you’ve bought the ASP.NET book I’ve written, you’ll probably be happy to know that I’ve added a new online chapter that deepens the initial cover of the Web API presented in chapter 9 of the book. If you’ve bought the book, just head to the web site and download the extra material associated with the book.

Modules: overriding properties

•February 14, 2013 • Leave a Comment

As we’ve seen in the previous post, we can add properties to an object exposed by a module through a technique known as augmentation. Even though there are some advantages associated with the approach shown (ex.: no need for loading scripts in a specific order), the truth is that we’re out of luck if we need to “override” a property defined in one of the files of the module. As I’ve said, in this case order of loading is important and there’s no way around it (after all, if we’re augmenting a property, it surely must have already been defined before being augmented, right?).

In order to illustrate this approach, we’ll rewrite the previous example. We’ll remove the jQuery dependency and will change the code so that each file defines  a single printValue (file 2 overrides and augments this method). The following snippet shows the code I’ve ended writing in each file (assume we’re using strict mode and that file 1 is loaded before file 2):

//file1
var obj = (function (baseModule) {
    var someValue = "private";
    function printValue(elemSelector) {
        return someValue;
    }
    return {
        printValue: printValue
    };
})();
//file2
(function (baseModule) {
    var someOtherValue = "private 2";
    //save reference to overriden method
    var otherModulePrintAnotherValue = baseModule.printValue;
    function printValueOverride(elemSelector) {
        return otherModulePrintAnotherValue() + "—" + someOtherValue;
    }
    //change reference to new method
    baseModule.printValue = printValueOverride;
})(obj);

If you compare this code with the one we had before, you’ll notice several differences. The most interesting part happens within the anonymous function defined in file2. As you can see, I start by saving a reference to the printValue method which was defined by the module introduced by file1. This reference is used by another function which will end up overriding the initial printValue method. Without this reference, it would be impossible to call the function after performing the override. From now on, you can simply call the overridden function like this (assuming we’ve got an element with ID set to info):

<script>
    "use strict";
    $("#info").text(obj.printValue());
</script>

And that’s it for now. Stay tuned for more.

More about modules: augmentation

•February 7, 2013 • 2 Comments

In the previous posts, I’ve introduced some basics aspects related to the implementation of the module pattern in JavaScript. Even though it introduces several benefits, there are some problems that might make you think that this pattern isn’t for you. For instance, if you’re working in a team where several members are contributing to the same module at the same time, then your best option is to spread  the module across different files.

Before going on, I must confess that splitting modules across different files isn’t really something I love. Whenever I’m facing this decision, I always try to re-check my code and see if I can refactor it so that a module is defined in a single file. There are, however, some cases where that isn’t possible and in those cases we need strategies like augmentation. The best way to illustrate it is to show an example. We’ll augment the module introduced in the previous post by adding a new method. Here’s one way to do it (notice that this code should be placed into a different JavaScript file):

var obj = (function(baseModule, $) {
    var someOtherValue = "private 2";
    function printAnotherValue(elemSelector) {
        $(elemSelector).text(someOtherValue);
    }
    baseModule.printAnotherValue = printAnotherValue;
    return baseModule;
})(obj, jQuery);
obj.printValue("#info");
obj.printAnotherValue("#info2");

Notice that this second anonymous function receives a reference to the original module which is being augmented (besides the jQuery global reference). There’s a slight gotcha with the previous code: you need to preserve the correct order when importing the files of the module. In the previous sample, that is not needed because none of the files uses properties defined in the other module, so we should do everything in our power to remove that dependency. Fortunately for us, we can remove that restriction by slightly changing the code:

var obj = (function (baseModule, $) {
    var someValue = "private";
    function printValue(elemSelector) {
        $(elemSelector).text(someValue);
    }

    baseModule.printValue = printValue;
    return baseModule;
})(obj || {}, jQuery);
var obj = (function(baseModule, $) {
    var someOtherValue = "private 2";
    function printAnotherValue(elemSelector) {
        $(elemSelector).text(someOtherValue);
    }
    baseModule.printAnotherValue = printAnotherValue;
    return baseModule;
})(obj || {}, jQuery);

According to the standard, the operator || will return the first expression when it’s convertible to true. If that isn’t possible, then it will return the second expression. In my example, we can use an empty object ({}) to ensure that we’re always working with a valid object within the anonymous functions that define the module. Since there is no dependency between the files, then this is more than enough for removing the order dependency introduced by our first snippet.

Even though the previous snippet allows one method to call another (ie, if, for instance, we need to call printValue from within printAnotherValue at runtime, then we should be fine), if we need to access  properties in order to override them, then we’re out of luck . In these cases, we need to change the and there’s no way to escape the need to preserve the loading order. That will be the topic for another post. Stay tuned for more.

JavaScript: more about the module pattern

•February 5, 2013 • Leave a Comment

In the previous post, we’ve started looking at the module pattern and how we can use it to write modular JavaScript code. I’ve ended the post mentioning that we still need to discuss an important topic before wrapping up the basics aspects associated with the pattern. If you’ve been following along, you know I’m talking about dependencies. In order to illustrate the topic, I’ll modify the previous example so that we use jQuery to print the message inside an element whose ID will be passed as a parameter. The next snippet shows our final code:

var obj = (function () {
    var someValue = "private";
    function printValue(elemSelector) {
        $(elemSelector).text(someValue);
    }
    return {
        printValue: printValue
    };
})();
obj.printValue("#info");

Now, if you’ve been doing JS for some time, you’ve probably noticed something which might get you worried: we’re depending on a global. Technically, $ is an alias to the jQuery global object. In other words, were depending on an implied global and whenever the JS interpreter engine finds one, it’ll have to walk the scope chain backwards until it finds a valid reference (in our example, it’ll walk until it gets to the global scope). Now, in our case, we’d end with an error if jQuery hasn’t been imported before our script gets run. Things could be worse though. For instance, suppose we were using the implied global in the left sign of an assignment expression. In that case, if the global didn’t exist, we’d end up creating a new one (if we were not running in strict mode).

Fortunately, there’s an easy solution for this kind of problem: I’m talking about global imports. Whenever you need a reference to a global variable within the closure created by the anonymous function, you just pass it as a parameter. The next snippet shows this strategy in action:

var obj = (function ($) {
    var someValue = "private";
    function printValue(elemSelector) {
        $(elemSelector).text(someValue);
    }
    return {
        printValue: printValue
    };
})(jQuery);

Even though we’re still using the $ alias, this time it refers to the local parameter defined by the anonymous function which is initialized with a reference to the jQuery global variable. With this strategy, we’ve ended with better code which is also faster.

Now that we already have gone through the basics, we’re ready to take a look at some more advanced scenarios. Stay tuned for more.

JavaScript: Getting started with the Module pattern

•February 4, 2013 • Leave a Comment

Today, the module pattern is one of the most used JavaScript patterns and that means that we, developers that need to write and build Web Apps, need to understand it well. In this post, I’ll introduce the pattern and I’ll come back to the topic in future posts. To the best of my knowledge, the pattern was introduced by Douglas Crockford and its main objective is to restrict the use of global variables and the pollution of the global namespace (leading to less collusions).

It goes without saying that global variables are evil. They’re really a source of unreliability and even insecurity. Reducing their usage leads to less collisions, which is a great thing in our days, where we need to use and mix several JavaScript libraries.

As we’ll see in the next paragraphs, the module pattern depends heavily in the use of anonymous closures. Anonymous closures are created by introducing an anonymous function which is executed immediately. The code run inside that function ensures privacy and state throughout the lifetime of the app. Notice also that this function will typically return an object which can be used to access that internal state. The following snippet illustrates the previous points:

var obj = (function() {
    var someValue = "private";
    function printValue() {
        return someValue;
    }

    return {
        printValue: printValue  
    };
})();
console.log(obj.printValue());

As you can see, we’re defining and invoking an anonymous function. The invocation part is really important. If you miss the () operator, you’ll end up injecting  a function in the current scope (which, in the previous example, is the global scope). In  other words, we would end up polluting the global namespace,  which is precisely the problem we’re trying to solve. As I said, the execution of the function ends up creating a closure. Since I had the good sense of using the var keyword when I introduced the someValue variable, I’ve ended up creating a local variable and it will only be available to code defined within that anonymous function (this is the privacy advantage I’ve mentioned before). The same thing happens to the internal printValue function: it’s only available to other code written within the anonymous function.

You’ve also noticed that the anonymous function returns an object with a single property. In practice, this is known exporting a value from the module. In this case, the single property of the exported object is a reference to the private printValue defined within the anonymous function and that means that we can call that function through the obj reference (as illustrated in the last line).

The previous code shows how to create a basic module, but we still have an additional aspect to discuss before wrapping up the modules: what about dependencies? I’ll leave that topic to a future post. Stay tuned for more.