Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Modular Programming with JavaScript
Modular Programming with JavaScript

Modular Programming with JavaScript: Modularize your JavaScript code for better readability, greater maintainability, and enhanced testability

eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Modular Programming with JavaScript

Chapter 1. What Are Modules and Their Advantages?

In this very first chapter, I will provide you with an overview of the modular design approach in application development as it relates to JavaScript applications.

I will also mention parallels between the modular style of application architecture and the real-life examples of this conceptual design.

Hopefully, as you read along, you'll be able to relate to at least some aspects of the modular design approach and start to see why this style of organizing your code can be extremely beneficial.

The main objective of this chapter is to create a familiar context for you, and to get you started on thinking the modular way as you create and organize your code. Soon, you will see that this approach can organically grow into a well-defined application architecture methodology.

We will start the chapter with a brief discussion on how we can organize our code based on specialization. Then we will look at how we can define modules based on the functionality that they provide.

The topics that are covered in this chapter are:

  • The simple rule to creating modules
  • A real life example of modules
  • A look at a non-modular example
  • Re-factoring into a more modular approach
  • Designing in a modular way

Prelude to modular programming

Many years ago, when I was taking my first computer programming course at college, I found myself having having difficulty organizing my code into functions and classes. I always wondered what kind of criteria I needed to keep in mind to qualify a chunk of code as a function, a class or a subclass. When should I break down one function into multiple functions or a class into multiple classes?

Of course, there were some rules and guidelines that I was familiar with such as: "a function should not be too long or should not do too many things; a class should be a blueprint of a data type" and so on. However, such rules and guidelines seemed abstract to me and I wanted to find a rule that was precise and applicable in all situations.

As I became more knowledgeable in programming concepts and gained more experience in application design, I was able to write more sophisticated code and organize my code better into functions and classes.

However, while my code was organized into well-defined functions and classes, such functions and classes still seemed scattered in different parts of the application. When I needed to make modifications to one piece of the application, I would be concerned about the impact that the change would have on other pieces and the functionality of the application as a whole.

As my applications grew larger and became more complex, the impact of the changes and enhancements became even more pronounced. There were more things things that could adversely affect the application if the application pieces were not designed properly.

Browser-based applications were particularly vulnerable to such impacts as different parts of the application could be manipulating the same element in the browser, which would produce unexpected behaviors and effects in other parts of the application.

On the other hand, making small changes to the application was a challenge on its own, as finding the best place to make such small changes was not always very obvious. Each piece of the application could be performing many different activities from manipulation DOM to writing to cookie to making AJAX calls.

What if I could make one part of the application responsible for only one type of functionality? What if only one part of the application would be responsible for all cookie-related functionality? What if only one piece would make AJAX calls to the server and provide the other pieces of the application with the returned data?

As we design functions and classes to specialize in doing very specific tasks, we can also bundle such functions and classes together to act as a specialized piece of the application responsible for providing one particular functionality. The key point here is to create specialized code packages.

This would mean that changes in how we read and write to cookies would only take place in the package that is responsible for cookie operations and such changes would have no impact on how AJAX calls are made to the server.

If we organize our code into specialized packages, (or modules as we will call them) we can easily achieve this goal of separation of concerns and responsibilities among our application pieces.

But before we can organize our code into modules, we need to see how chunk of code can be considered a module

The simple rule for creating modules

I need to emphasize on the fact that modular programming is not some magical and mystical design concept and pattern that is hard to grasp and even harder to implement. It is really just a practical approach to organizing our code in such a way that each chunk of code only does a very specific and specialized task.

The idea is that each module is a loosely coupled piece of the application, a building block that, along with other pieces (and other modules), creates an ecosystem, that is your application.

So here is the simple rule for creating modules: "If a piece of your application provides a specialized functionality, it can be made into a module that can also be reused in other applications."

I mentioned previously that I was looking for a "precise" rule to help me organize my application code but as my experience has shown, there is no such precise rule other than what I mentioned above, which is in fact not a rule but a guideline. And as a guideline, there is flexibility in what can be considered a module or not. This can be best decided both at the design time and as the application evolves since the application needs can change over time.

A real-life example of modules

Let's consider a familiar modular system. You are most likely reading this book in a place that has electricity and there are many electric outlets in the walls surrounding you. This system enables you to plug in various electrical devices into the outlets and each one of these devices is designed to do a very specific task.

Consider the electrical devices that are plugged into some of these outlets: microwaves, electric kettles, washers, dryers, and so on.

None of these devices care if they are plugged into the electrical outlet in your house or your neighbor's house. They are designed to do their specific task and functionality when they are plugged in and when the power is on, regardless of whose house they are in.

Our application modules should follow the same philosophy. This means, regardless of where in the application they are plugged in and even regardless of what application they are plugged into, they should do their specific task and only their specific task.

Also, in exactly the same way that an electrical device can easily be unplugged from the wall outlet, a code module should be designed in such a way that it can easily be decoupled and removed from your application.

Furthermore, as the removal of one electrical device has no impact on the functionality of other devices that are plugged into your electrical system, the removal of a code module or a series of code modules from your application should not have any effect on the functionality of the other parts of your application.

This decoupling should also have no effect on the application as a whole, other than perhaps just losing the specific functionality that was provided by that particular module or group of modules in your application.

In this book, we will explore how creating modules will help in designing better specialized code pieces that can easily be plugged into and unplugged from our applications. We will also see how modular architecture provides for a more robust and flexible application as a whole.

We will discover how this kind of architectural approach leads to huge advantages in many aspects of our application fundamentals such as code usability, maintainability, testability, and many more.

I hope now you are curious enough to at least consider modular programming in general and JavaScript modular programming in particular as a possible approach for your future application design.

In further chapters, we will apply the same principles that we discussed regarding electrical outlets and appliances to our code modules, in both the design and implementation phases.

A look at a non-modular example

Let's consider an extremely simple example and see how the (somehow) specialized modular approach differs from a non-modular one.

We start by writing a couple of functions in the traditional way, as following:

function doAddition(num1, num2){
  return num1 + num2;
}

function doSubtraction(num1, num2){
  var result = null;
  if(num1 > num2){
  result = num1 - num2;

  }else{
    result = num2 - num1; 
  }
  return result;
}

console.log(doAddition(3,2)); // displays 5

console.log(doSubtraction(3,2)); // displays 1

As you can see in the above code, we have two independent functions for doing simple additions and subtractions and there is no relation between the two, other than the fact that they both operate on the two passed-in numbers (numeric values).

If we had implemented these functions in an application and were to do the identical operations in a different application, we most likely would either rewrite the same functions in that application from scratch or we would copy/paste the code from this application into the other one.

What if we now decided to also do multiplication, division, and other related calculations in our application using the same approach?

Well, one way would be to just continue writing independent functions as above and add them to our application. This approach could work and would get the job done, but probably not in the best way, since as the code grows it will become more disorganized and chaotic.

By using this approach, not only would we be polluting the global namespace with a bunch of global functions that could possibly collide with other global functions of the same name. We would also end up with scattered pieces of code that had not been packaged together based on their functionality and specialization.

If all such functions do mathematical calculations of one kind or another and that is the commonality that they all have, how about if we create a package (module) that specializes in mathematical calculations?

This would allow us to have a specialized package that regardless of the application that it is hosted in, would always provide the same specialized functionality.

Let's even imagine a step further and assume that we created this package in a separate JavaScript file that can be added as an independent module to any application.

Even better, how about if this module only would get added (requested from the server, in the case of a client side web application) to the application at runtime, and only when needed?

This type of implementation would give us the ability to load chunks, pieces, or modules of the code when needed at runtime and then unload them when the application does not need them anymore. This would enable us to cut down on the footprint of our application on the client side while providing all the necessary functionality as needed and on demand.

Such an approach can also be very useful on mobile devices which have limited bandwidth and resources to be leveraged.

Rest assured that I do intend to explore all such possibilities with you in the later chapters of this book.

Re-factoring to a more modularized approach

Let's consider re-factoring the two functions that we looked at previously and putting them together in a more specialized package (class or module) called, CalculationHandler, as shown below:

function CalculationHandler(){
  CalculationHandler.result = null;
}

CalculationHandler.doAddition = function(num1, num2){
  return num1 + num2;
};

CalculationHandler.doSubtraction = function(num1, num2){

  if(num1 > num2){
    CalculationHandler.result = num1 - num2;

  }else{
    CalculationHandler.result = num2 - num1; 
  }
  return CalculationHandler.result;

};

console.log(CalculationHandler.doAddition(3,2)); // displays 5
console.log(CalculationHandler.doSubtraction(3,2)); // displays 1

As you can see in this "module" (and I use the term loosely here; you will see why in later chapters), I am using a function object and adding properties (methods) to this object. These methods do specialized tasks related to the overall functionality of the object (module), such as addition and subtraction.

Note

A note about our module here

If you are more experienced in JavaScript programming, you are probably thinking that the way I have created this module is probably not the best way to create a real module in JavaScript, and you are right! But for now, the big idea here is that any piece of code that does a specialized task can be tagged as a module, for the most part.

However, there are certainly better ways to write more robust and extensible modules in JavaScript. For instance, creating a module can be accomplished much better by using the Module Design Pattern, which we will get to explore a lot further in later chapters of this book.

Designing in a modular way

In the early stages of designing an application, one of the most important steps is to decide on the functionality that the application needs to provide. This of course, is based on the overall purpose of the application and the type of application that you are designing.

Based on such requirements, in the design phase, you should try to break down the overall functionality (the big picture) of the application into smaller and specialized pieces. Then, you can determine if such pieces already exist, either in the form of third-party libraries or the code that you have already written for a different application.

If you already have your own chunks of reusable code designed in a modular fashion (most third-party libraries are designed in such a way too), it would be much easier and quicker to connect these pieces together and use them in your new application. This would be the same as putting various Lego blocks together to create a play structure.

This type of approach is very important and fits quite well within an Agile development environment. This enables you to work on well defined, specialized modules as you need them and as new application requirements are defined. Also, as you create your code based on modules, you are able to prevent tight coupling among your application pieces.

On the other hand, this approach allows different developers to work on different pieces (modules) of the same application, independently of each other. Another advantage is that modules can be tested separately and in different environments before being added to the application.

In time and with more experience in modular application design and implementation, you will become better at deciding how to distinguish and design your modules. However, it is not realistic to think you can come up with the complete list of all the modules that you could ever need in your application, in the first attempt.

That is because applications evolve and requirements change over time. You may need to create new modules, or modify current ones, or decide to use a different module or library altogether to accommodate such changes in the requirements.

The key advantage of modular design is the flexibility that it provides. Dealing with all the situations mentioned above is a lot easier and requires a lot less effort in a modular architecture. It will also mitigate the impact that adding, removing, or modifying a module could possibly have on the application as a whole.

In the following chapters, you will see how we can create simple and complex modules and how they will be added to our application as loosely coupled pieces.

You will also see how we can load such modules dynamically and on demand when we need them in our application.

So, let's get ready for an exciting journey into our future application design, using modular architecture.

Summary

In this chapter, we tried to get an overview of the concepts behind modular programming in general and how such concepts can be used in JavaScript applications in particular.

We saw that this approach is essentially based on creating packages of specialized code that do very specific tasks.

We also made parallels between how modules are designed in real life and our application modules, so that we can translate the similarities into our own application design approach.

While the term "module" can be used to refer to different things in the code, we will take this terminology to refer to a certain style of programming and architecture in our JavaScript application design approach in later chapters.

However, before we completely dive into the more technical aspects of JavaScript modular programming, it is a good idea to review the fundamentals of object-oriented programming in JavaScript in the next chapter. This will allow us to establish a solid foundation for more technical chapters as we move forward.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Design and build fully modular, modern JavaScript applications using modular design concepts
  • Improve code portability, maintainability, and integrity while creating highly scalable and responsive web applications
  • Implement your own loosely coupled code blocks that can power highly maintainable and powerful applications in a flexible and highly responsive modular architecture

Description

Programming in the modular manner is always encouraged for bigger systems—it is easier to achieve scalability with modular programming. Even JavaScript developers are now interested in building programs in a modular pattern. Modules help people who aren’t yet familiar with code to find what they are looking for and also makes it easier for programmers to keep things that are related close together. Designing and implementing applications in a modular manner is highly encouraged and desirable in both simple and enterprise level applications. This book covers some real-life examples of modules and how we can translate that into our world of programming and application design. After getting an overview of JavaScript object-oriented programming (OOP) concepts and their practical usage, you should be able to write your own object definitions using the module pattern. You will then learn to design and augment modules and will explore the concepts of cloning, inheritance, sub-modules, and code extensibility. You will also learn about SandBoxing, application design, and architecture based on modular design concepts. Become familiar with AMD and CommonJS utilities. By the end of the book, you will be able to build spectacular modular applications in JavaScript.

Who is this book for?

If you are an intermediate to advanced JavaScript developer who has experience of writing JavaScript code but probably not in a modular, portable manner, or you are looking to develop enterprise level JavaScript applications, then this book is for you. A basic understanding of JavaScript concepts such as OOP, prototypal inheritance, and closures is expected.

What you will learn

  • Understand the important concepts of OOP in JavaScript, such as scope, objects, inheritance, event delegation, and more
  • Find out how the module design pattern is used in OOP in JavaScript
  • Design and augment modules using both tight augmentation and loose augmentation
  • Extend the capabilities of modules by creating sub-modules using techniques such as cloning and inheritance
  • Move from isolated module pieces to a cohesive, well integrated application modules that can interact and work together without being tightly coupled
  • See how SandBoxing is used to create a medium for all the modules to talk to each other as well as to the core
  • Use the concepts of modular application design to handle dependencies and load modules asynchronously
  • Become familiar with AMD and CommonJS utilities and discover what the future of JavaScript holds for modular programming and architecture

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 28, 2016
Length: 274 pages
Edition : 1st
Language : English
ISBN-13 : 9781785883996
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : Jul 28, 2016
Length: 274 pages
Edition : 1st
Language : English
ISBN-13 : 9781785883996
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 115.97
Mastering JavaScript Object-Oriented Programming
€36.99
Modular Programming with JavaScript
€36.99
Modern JavaScript Applications
€41.99
Total 115.97 Stars icon

Table of Contents

11 Chapters
1. What Are Modules and Their Advantages? Chevron down icon Chevron up icon
2. Review of Important JavaScript OOP Concepts Chevron down icon Chevron up icon
3. Module Design Pattern Chevron down icon Chevron up icon
4. Designing Simple Modules Chevron down icon Chevron up icon
5. Module Augmentation Chevron down icon Chevron up icon
6. Cloning, Inheritance, and Submodules Chevron down icon Chevron up icon
7. Base, Sandbox, and Core Modules Chevron down icon Chevron up icon
8. Application Implementation – Putting It All Together Chevron down icon Chevron up icon
9. Modular Application Design and Testing Chevron down icon Chevron up icon
10. Enterprise Grade Modular Design, AMD, CommonJS, and ES6 Modules Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5
(2 Ratings)
5 star 0%
4 star 50%
3 star 50%
2 star 0%
1 star 0%
Konstantin Jun 06, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
this is a fantastic book that teachers you how to build modular applications in javascript... and i am very happy i stumbled on it. It takes a very systematic approach towards the topic (building javascript applications using MVC/MV* patterns). I think the author has done a great job! There are some typos in the book though(that pretty much applications to all books)... that said, i cant recommend it enough! get it :-)
Amazon Verified review Amazon
RC Mar 26, 2018
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Had this book been published at the same time the ES5 standard was released (2009), I would give it 5 stars. The author does an excellent job at explaining how to create modules using IIFE (Immediately Invoked Function Expression), module augmentation techniques, OOP concepts, structural & behavior design patterns ( Facade, Mediator, Pub/Sub) and implements an excellent modular SPA (Single Page App) architecture based on Nicholas Zakas's 'Scalable JavaScript Application Architecture.'Because it was published after the release of the ES6/ES2015 standard, most of the content is dated. Since the release of ES2015 modules and modern browsers now supporting ES6 Modules, IIFE's are no longer the preferred technique to create modularity. The author dedicates only 4 pages to ES2015 modules.This book should have been about:1. How to migrate legacy IIFE modules to ES6 Modules2. How to use transpilers like Babel to create modules in ES6 and transpile back to ES5 module APIs (AMD, CommonJS, etc.).3. How to use tools like Webpack to support non-ES6 legacy browsers.4. Implementing the latest techniques for ES6 modules.In conclusion, the majority of the content is dated, however, one can still learn a lot on creating modularity with IIFE's and SPA modular architecture.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.