上QQ阅读APP看书,第一时间看更新
Modules
As mentioned in Chapter 1, The Importance of Good Code, clean code should be structured in a modular way. In the next few sections, we'll introduce you to the concept of modular design, before explaining the different module formats. Then, for the rest of the chapter, we will begin composing our project by incorporating existing Node modules.
But first, let's remind ourselves why modular design is important. Without it, the following apply:
- Logic from one business domain can easily be interwoven with that of another
- When debugging, it's hard to identify where the bug is
- There'll likely be duplicate code
Instead, writing modular code means the following:
- Modules are logical separations of domains—for example, for a simple social network, you might have a module for user accounts, one for user profiles, one for posts, one for comments, and so on. This ensures a clear separation of concerns.
- Each module should have a very specific purpose—that is, it should be granular. This ensures that there is as much code reusability as possible. A side effect of code reusability is consistency, because changes to the code in one location will be applied everywhere.
- Each module provides an API for other modules to interact with—for example, the comments module might provide methods that allow for creating, editing, or deleting a comment. It should also hide internal properties and methods. This turns the module into a black box, encapsulating internal logic to ensure that the API is as minimal as is practical.
By writing our code in a modular way, we'll end up with many small and manageable modules, instead of one uncontrollable mess.