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