Chapter 9
Using Modules

Well-designed software is cohesive. Cohesion is when a piece of code is narrow, focused, and does one thing well. A good designer strives to achieve cohesion at all levels: functions, classes, and especially files.

A well-designed file should contain only things closely related to each other. Like things should be together in one file, and unlike things should be apart from each other in different files. In addition to making the code cohesive, small files focused on one particular concern also promote better reuse.

Nontrivial applications need many functions and multiple classes with intricate dependencies. Having the ability to access everything from everywhere leads to chaos, confusion, and errors. A piece of code should be well contained; programmers should be able to clearly specify what is available for others to use and intentionally declare things they need from the outside. This is where JavaScript modules come in.

JavaScript modules are used to modularize code—that is, to divide code into parts that have different concerns, but they may need to depend on one another. For example, each component and service class you create in, say, React and Angular will belong to separate modules. Each group of functions related to a common set of operations may belong to a module. In modern JavaScript, any nontrivial application will be made up of modules. Use modules to define clear boundaries in code and to specify what’s internal to your file and what may be used from the outside.

A JavaScript module is a well-encapsulated file. As a creator of a module, you’re responsible for clearly specifying what you need—the imports—and what you provide for others to use—the exports. Within a module, you can’t use what you haven’t imported. Likewise, the users of your module can’t use what you haven’t exported. This prevents accidental and unintentional dependencies in code and thus reduces errors.

By learning about modules, you will be able to understand how they’re used in code that use libraries and frameworks, like React and Angular. Furthermore, you will be able to decide how to break your large applications into well-structured parts. In this chapter you’ll learn how to create modules, export code from modules, and import code into other modules. Along the way you’ll examine the consequences of the decisions you make.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.21.109