Monday, November 25, 2013

Modularize with RequireJS

What is modularization? Modularization breaks large code base into smaller blocks of manageable code, thereby improving maintainability, reusability and extensibility. Modularization when done properly decouples the functionality and reduces the dependencies.

Why modularization? Imagine a large application with huge amount of code, without encapsulation, with conflicting global scope, with huge dependencies, with tight coupling and developed with JavaScript. Now imagine you need to support this huge code base. Won’t it be easier if the code is properly managed with loose coupling and reduced dependencies?

Modularization sounds great and has been a tenet in all traditional programming languages such as C#, VB, Java. Developers in these languages code modularized code without even thinking about it. Unfortunately this is a big deal in JavaScript as the current version of JavaScript does not provide a clean way of modularizing the JavaScript code. So what to do now?

Thanks to the RequireJS, writing modular code is JavaScript is easier and you can do it now.

In this blog I will walk you through how to easily modularize your javascript code using one of the most popular and commonly used JavaScript library, RequireJS. RequireJS has several other advantages in addition to modularization, but in this blog I will only focus on modularization and walk you through converting a small javascript code into a modular javascript code using RequireJS.

Here is a small javascript code which calculates the discount for a product in an ecommerce application

function getPrice() {
    console.log("Getting price")
    return 120;
}

function calculateDiscount(price)
{
    console.log("Calculating discount")
    var discount = 10;
    return price * (100 - discount) / 100;
}

var actualPrice = getPrice();
var price = calculateDiscount(actualPrice);
alert(price);

The above code can be huge if have thousands of products and several discount promotions. Typically in server side code using C# we classify this code into classes as mentioned below.
  • Product object which returns the price of a product
  • Discount object which calculates the discounted price based on the promotion
  • Main or caller class which calls into this calculation 

RequireJS provides the similar approach in JavaScript. We can define Product, Discount and Main modules in Javascript and partition this code. Here is the modularized code using RequireJS

product.js
define([], function () {
    return {
        getPrice : function () {
            console.log("Getting price")
            return 200;
        }
    }
});

discount.js
define([], function () {
    return {
        calculateDiscount : function(price) {
            console.log("Calculating discount")
            var discount = 10;
            return price * (100 - discount) / 100;
        }
    }
});

main.js
require([product', discount'], function (product, discount) {
    var actualPrice = product.getPrice();
    var price = discount.calculateDiscount(actualPrice);
    alert(price);
});

As you see the product.js and discount.js scripts are enclosed with define attribute, but the main.js is enclosed with require attribute. The primary difference between these two are, require attribute defines and runs the code within. Hence you need require if you want to execute immediately. This is similar to the document.onload event.

On your page you just need to include the main.js and all the other javascript files will be automatically loaded by RequireJS. Here is the syntax for the script include tag.

<script data-main="scripts/main" src="scripts/require.js"></script>

RequireJS makes modularization easy and doable with today’s technologies. 

No comments:

Post a Comment