Preface

Long after the printing press was invented, publishing books remains a challenging endeavor. Yes, there’s typically an author (or authors) who scribble the content wherever and whenever they find time to do so. But there’s also a content editor, tasked with helping the author transform their stream of consciousness into a relatable story that’s not too dry to read—something to be especially careful about when it comes to technical or business books. We have the technical reviewers, watchful subject-matter experts on the lookout for egregious mistakes in technical definitions or interpretations. And lastly, of course, we have the copyeditor, the typo linters of prose and last bastion of proper grammar. Thus far, however, we’ve barely scratched the surface: everyone mentioned here is interested mostly in the contents of the book, but there are other aspects to the bookmaking process as well. There’s also, as an example, the typesetter, whose job is to ensure that the book looks good when it goes to print—bidding good riddance to orphans and widows, poorly wrapped lines of code, and so much more. Someone has to design the cover, and another person must approve the table of contents for the first draft so that the author gets a contract. In addition, several people oversee the process that culminates in the book going to press, usually referred to as production. Once copies are printed, they need to be distributed. Eventually, the book hits the shelves (physical or otherwise) and starts selling. Someone buys the book and finally starts to read it. We could write entire books about the purchase transaction alone.

The complexity of the whole process is mind-boggling, and yet, to each individual, it’s not that complicated. The author, for example, merely has to write a few hundred words every day. Where did all that complexity go? There’s a reason the process is so compartmentalized: we’re not that good at handling high-level complexity. Breaking it into single responsibilities (such as “write content,” “improve how prose flows,” “review technical concerns,” “fix grammar mistakes,” “typeset for production,” or “handle purchases”) is what makes the process simpler for individuals working on the mammoth project that is writing a book, or just about any business enterprise.

Publishing is merely an example—we could do this exercise with just about anything. Pick an object on your desk, any object. Think about how it got there. Now zoom out, think some more: How was it made? What is it made of? How many people were involved in manufacturing each piece, assembling it, perfecting it, and getting it to the store where it was bought? Is it a fruit? How many people were involved in planting it, fighting off pests, pruning plants, packaging the fruit, and getting it to the store where it was bought?

Software is not all that different, except complexity is all around us. At the deepest zoom levels, we find constraints defined by physical constants such as the speed of light, individual bits and hardware, interrupt calls, assembly language, and much more. Zooming out, we find the megastructures of the technology sector, which handle everything from search queries to payment processing. Somewhere in the midst of all this complexity, there’s us developers and the projects bestowed upon us.

We hardly stop to think about the complexity underlying everyday objects and interactions, since doing so would be paralyzing. Instead, we hide solutions behind abstract interfaces, so much that they become—in our minds—the interface. Some of these interfaces map well to the abstracted implementation, and they feel great. Others don’t map all that well to the implementation, and we end up feeling confused and frustrated. Software is not at all different. We don’t want to think about the system as a whole, and virtually everything we work with sits behind interfaces that are simpler to use and understand than their underlying implementations.

Who Should Read This Book

This book is meant for developers, enthusiasts, and professionals with a working knowledge of JavaScript and ES6.1 These developers, and anyone interested in learning more about writing modular code that’s readable, maintainable, and scalable, even beyond the JavaScript language, shall benefit from reading Mastering Modular JavaScript.

Why Modular JavaScript?

I started toying with Node.js—and, unbeknownst to me, getting into a serious relationship with JavaScript—at about the same time that I discovered open source and fell in love with its practices. Coming from the closed-source landscape in C#, the open source ecosystem around Node.js gave me a new perspective and joy in figuring out how to write robust code that others find pleasant enough to consume. It’s with this background that I find myself always pondering about how an interface should be defined, who would be consuming it, and how they’d like to spend their time doing something else than figuring out what we originally intended them to do.

The goal of this book is to offer an affable way of becoming a successful module author. It’s not that writing JavaScript modules is particularly difficult; however, following sound design practices to ensure that we deliver the right amounts of simplicity and flexibility so that consumers can rely on modules to be simple most of the time (but flexible when it matters) while keeping internal complexity in check—is hardly a trivial task. I wrote bits and pieces about proper application design in JavaScript Application Design2 and for the Pony Foo blog, but I’ve been yearning to publish something more comprehensive that was exclusively dedicated to reasoning about, designing, and writing modular code.

Though I couldn’t find any books that addressed the subject from a JavaScript point of view, you can easily find other books that touch on the subject of modular code, such as Code Complete by Steve McConnell (Microsoft Press) or Clean Code by Robert C. Martin (Prentice Hall), and leverage their teachings in your JavaScript development efforts. Mastering Modular JavaScript is an attempt to draw attention away from what others think you should be doing, and instead enable you to come to your own conclusions about what you should be doing and why—without imposing axiomatic rules that only contribute to what artificially self-proclaims and positions itself as “clean code.”

Without being too overt, this book tries to explain how you could be writing modular code. Instead, we’ll try to shed light on the fundamentals behind modular architecture, and its history when it comes to JavaScript, so that you have a better understanding of what it means to write modular applications and what’s to be gained from doing so.

While there are heaps of books on proper application design, there isn’t a lot of material to be found on the topic of modular application design, let alone modular JavaScript application design—hence this book. While the majority of the advice, musings, and teachings in this book aren’t at all specific to JavaScript, the fresh focus on JavaScript means you’ll be learning about how to write modular web applications while keeping in mind the quirks that make the web such a unique platform and make JavaScript special in many ways.

Rather than rely on long-winded, pages-long, thoroughly analyzed, concrete examples, the book hopes to challenge you to apply its passages to the problems that you’re trying to address in your own programs, and coming to your own realizations by weighing the benefits and drawbacks of taking one of a few possible approaches. In software, there is no such thing as one-size-fits-all, and you’re often going to leverage your own best judgment to decide how to write it. All software adapts to the context that surrounds it, and if you’ve done any work at all involving software deployments or releases, then you surely are intimate with exactly how hard it is to cram the same piece of software into different execution environments.

Just as with Practical Modern JavaScript, this book has the goal of establishing a baseline, bit by bit. After having learned all about the latest language features in Practical Modern JavaScript, we’ll use this book to learn all about modular design thinking. This incremental and modular approach is meant to be pervasive in both books, across each chapter, and each section.

How Is This Book Organized?

Chapter 1 discusses the evolution of modularity in the context of JavaScript, from the early days of embedding JavaScript in onclick attributes, to CommonJS and finally native ECMAScript modules. It then looks at the benefits of writing self-contained code, and of doing so at every level of a system: services, applications, components, modules, functions, blocks, and so on.

Chapter 2 covers the essentials of modular design, giving you a foundation from which you can write modules that are conscientious of their API surface, how it’s (in all likelihood) going to be consumed, where the responsibilities lie, and what belongs on the interface.

A good portion of Chapter 3 is devoted to understanding the kinds of problems you should be solving, and how to do so while keeping an eye on the way the module and its interface may evolve, and being shy about abstractions while waiting for clear patterns to emerge. This chapter prods beneath the surface to get you thinking of best practices around documentation, error handling, and following your own reasoning by applying your own context to the problem that is being resolved.

In Chapter 4, we get comfortable talking about internal complexity, tight coupling, and weighing the merits of frameworks and conventions. The bulk of this chapter is spent discussing some of the many ways in which we can reduce complexity by refactoring our code. We then discuss the role of state in relation to complexity, and how it can be mitigated. Data structures play a role as well, as selecting the right ones is both challenging and immensely rewarding when it comes to keeping complexity in check.

Chapter 5 is specifically about JavaScript, detailing how we can leverage modern language constructs to write clear programs. This chapter also examines patterns such as inheritance and composition, leading into a discussion about which option is better, depending on your use case. The chapter is rounded out by tackling classic patterns like revealing modules, object factories, event emitters, and JSON message passing.

Chapter 6 describes the mindset of a battle-hardened module developer, addressing security concerns and dependency management, build and integration processes, interfaces and abstractions, and generally a potpourri of module design advice and best practices.

Those of you who are already familiar with the history of modularity when it comes to JavaScript would do well to, at the very least, skim through the history lessons in the first chapter. If you’re more of the type who’s comfortable jumping around the pages in a book, I would still recommend reading through every chapter, given this relatively short book is more of a story to be told about well-reasoned programs than it is a compendium of recipes.

Conventions Used in This Book

The following typographical conventions are used in this book:

Italic

Indicates new terms, URLs, email addresses, filenames, and file extensions.

Constant width

Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords.

Note

This element signifies a general note.

O’Reilly Safari

Note

Safari (formerly Safari Books Online) is a membership-based training and reference platform for enterprise, government, educators, and individuals.

Members have access to thousands of books, training videos, Learning Paths, interactive tutorials, and curated playlists from over 250 publishers, including O’Reilly Media, Harvard Business Review, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Adobe, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, and Course Technology, among others.

For more information, please visit http://oreilly.com/safari.

How to Contact Us

Please address comments and questions concerning this book to the publisher:

  • O’Reilly Media, Inc.
  • 1005 Gravenstein Highway North
  • Sebastopol, CA 95472
  • 800-998-9938 (in the United States or Canada)
  • 707-829-0515 (international or local)
  • 707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://bit.ly/mastering-modular-javascript.

To comment or ask technical questions about this book, send email to .

For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Watch us on YouTube: http://www.youtube.com/oreillymedia

Acknowledgments

There are a lot of people to thank for Mastering Modular JavaScript coming to fruition. First and foremost is Virginia Wilson, the main content editor in charge of this book and the Modular JavaScript series at O’Reilly. She offered insight where it counted, was very understanding when my schedule tightened and the writing slowed to a trickle, and always kept an extremely positive attitude about things!

The technical reviewers were also out of this world. Mathias Bynens focused on making sure my comments around the ECMAScript specification were up to par, as usual. Ingvar Stepanyan always seems ready to jump at the chance to help out with technical reviews for my books, and he’s always offering unique points of view that result in clearer descriptions and more thorough examples, I’m incredibly grateful for his work. Adam Rackis has also been super helpful during technical review for the series, always providing solid commentary about bits that needed to be corrected, better fleshed out, or clarified.

I would be remiss if I didn’t call out everyone who backed the Indiegogo campaign for the Modular JavaScript book series back in 2016. Thank you for placing your trust in me when these books were merely an idea, injecting me with a large dose of enthusiasm early on. If we ever run into each other, the beers are on me!

In no particular order:

Aaron Endsley, Aaron Hans, Aaron Olson, Aaron Wells, Adam Rackis, Adi Purnama Mutiara, Adrian Li, Adrian Rand, Agustin Nicolas Polo, Alan Chandler, Alasdair Shepherd, Alejandro Nanez, Alexis Mills, Allen Dean, Anastasios Alexiou, Andrea Giammarchi, Andres Mijares, Andrew Broman, Andrew Kenward, Andrew Shell, Andrew Van Slaars, Andrey Golovin, Angel Ramirez Morel, Anna Vu, Anselm Hannemann, Anthony Casson, Arnau Pujol, Arnis Lupiks, Artur Jonczyk, Aziz Khoury, Barney Scott, Beau Cronin, Ben Lagoutte, Ben Mann, Benjamin Bank, benjamintpoon, Benny Neugebauer, Bishal Pantha, Bran Sorem, Brent Huffman, Bruce Hyatt, Burton Podczerwinski, Béla Varga, Ca-Phun Ung, Cameron Stark, Carlos López, Casper de Rooij, Chad Thoreson, Charles Herman, Charles Rector, Charlie Hill, Chase Hagwood, Chris Fothergill, Chris Weber, Christopher Dresel, Christopher Gonzales, Christopher Hamilton, Christopher Scott, Cindy Juarez, Claudia Hernández, Constantin Chirila, Cris Ryan Tan, Dallen Richard Loder, Dan Hayden, Dan M., Dan Perrera, Dan Rocha, Daniel Cloud, Daniel Egger, Daniel Sleeth, David Ershag, David G. Chaves, David González Polán, David Hobbs, David Lemarier, Dayan Barros, Dejan Cencelj, Denise Darmawi, Derick Rodriguez, Derik Badman, Dick Grayson, Dmitry Goryunov, Don Hamilton III, Donald Gary, Doug Chase, Dumitru Florin Gabriel, Eder Sánchez, Edgar Barrantes, Edouard Baudry, Eduardo Rabelo, Eric Lezotte, Ersan Temizyurek, Ezequiel Cabrera, Fabian Marz, Fabio Vedovelli, Fabrice Le Coz, Federico Foresti, Fer To, Fernando Ripoll Lafuente, Flavio Spaini, Fran Nunez, Francesco Strappini, Francisco Cerdas, Fredrik Forsmo, Fredrik Lexberg, Gabor Dolla, Gabriel Chertok, Gabriel García Seco, Gergo Szonyi, Giovanni Londero, glennjonesnet, Gorshunov Vladimir, Guy Tepper, Hamish Macpherson, Hanslutter Fomben, Henk Jan van Wijk, Hernan Chiosso, Horváth László Gábor, Hugo Lopes, Ian B. De La Cruz, Ian Doyle, Ian McCausland, Ignacio Anaya, Istvan Szmozsanszky, Ivan Saveliev, Ivan Tanev, J. Singh, Jack Pallot, Jack W McNicol, Jaime García, Jake Smith, Janderson Martins, Jani Kraner, Jared Moran, Jason Broyles, Jason Finch, Jean Osorio, Jeffrey Borisch, Jelena Jovanovic, Jennifer Dixon, Jeremy Tymes, Jeremy Wilken, Jia Fei Fei, Jiaxing Wang, Joachim Kliemann, Joan Maria Talarn, Johannes Weiser, John Engstrom, John Fogarty, John Johnson, Jon Saw, Jonathan Boiser, Joostc Schermers, Josh Adam, Josh Magness, José Esparza, jsnisenson, Juan Lopez, Junrou Nishida, Jörn Flath, Karthikeya Pammi, Kevin Gimbel, Kevin Rambaud, Kevin Scheffelmeier, Kevin Youkhana, kgarbaya, konker, Kostas Galanos, Kris Bulman, Kyle Simpson, Lalit Agrawala, Lea P., Leonardo Di Lella, Lidor Lapid, mailtorenil, Marc Grabanski, Marco Martins, marco.scarpa, Marcus Bransbury, Mariano Campo, Mark Kramer, Martijn Rouwendal, Martin Ansty, Martin Gonzalez, Martin Luna, Massimiliano Filacchioni, Mathias Bynens, Matt Riley, Matt Webb, Matteo Hertel, Matthew Bagwell, Mauro Gestoso, Max Felgenhauer, Maxwell Chiareli, Michael Chan, Michael Erdey, Michael Klose, Michael Kühnel, Michael Spreu, Michael Vezzani, Mike Kidder, Mike Parsons, Mitchell Gates, Nathan Heskew, Nathan Schlehlein, Nick Dunn, Nick Klunder, Nicolás Isnardi, Norbert Sienkiewicz, Oliver Wehn, Olivier Camon, Olivier Van Hamme, Owen Densmore, P. Ghinde, Patrick Nouvion, Patrick Thompson, Paul Aeria, Paul Albertson, Paul Cooper, Paul Grock, Paul Kalupnieks, Paul Kamma, Paul Vernon, Paula Penedo Barbosa, Paulo Elias, Per Fröjd, Peter deHaan, Peter Holzer, Peter Piekarczyk, peterdoane, Phan An, Piotr Seefeld, Pranava S Balugari, Rahul Ravikumar, Randy Ferrer, Renato Alonso, Rey Bango, Reynaldo Tortoledo, Ric Johnson, Ricardo Pereira, Richard Davey, Richard Hoffmann, Richard Weltman, Riyadh Al Nur, Robert Buchholz, Ron Male, Ryan Castner, Ryan Ewing, Rylan Cottrell, Salvatore Torcivia, Sean Esteva, Sebastian Brieschenk, Sergey Efremov, Sergey Melnikov, Shane Eckel, Shaunak Kashyap, Shawn Searcy, Simeon Vincent, simonkeary, Stefan Boehm, Steve Mahony, Steven Kingston, Stoyan Delev, Stuart Robson, Sumit Sarkar, Swizec Teller, Szabolcs Legradi, Tanner Donovan, Ted Young, Thee Sritabtim, Thomas Noe, Thomas Schwarz, Tim Goshinski, Tim Osborn, Tim Pietrusky, Tony Brown, Tudosa Razvan, Ture Gjørup, Umar Farooq Khawaja, Uri Chandler, Victor Rosell, Vinay Puppal, Vladimir Bruno, Vladimir Simonov, Vladimir Zeifman, Wayne Callender, Wayne Patterson, Wee Keat Liew, Wes Bos, Wonmin Jeon, Yann LE CORRE, Yevgen Safronov, Yonatan Mevorach, youbiteme, Zach Gottlieb, Zachary Hawkins, Zane Thomas, 坤福 曾, @agolveo, @amstarri, @bondydaa, @cbergenhem, @cde008, @changke, @dhtrinh02, @dlteron.green, @eduplessis, @eonilsson, @fogarty.tj, @fortune, @gm.schlereth, @illusionmh, @jcnoble2, and @michael!

As usual, I’d also like to thank my wife, Marianela, for always standing right beside me through the emotional roller coaster that is writing these books. I don’t know how she does it.

1 ES6 effected a profound change in the JavaScript language, introducing multiple syntax improvements and a few handfuls of new methods. This book assumes familiarity with JavaScript after ES6. You can learn more about ES6 syntax by visiting the Pony Foo blog for a crash course.

2 JavaScript Application Design is a book I published through Manning in 2015. It revolves around build processes, but also features chapters on managing complexity, sensible asynchronous flow control code, REST API design, and JavaScript testing concerns.

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

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