Chapter 10. Achieving loose coupling


This chapter covers

  • Recognizing the signs of tightly coupled code
  • Strategies for reducing coupling
  • Message-oriented programming

Loose coupling is what allows you to make changes in different areas of your code without worrying that you’ll break something elsewhere. It allows you to work on one feature while your coworker tackles another. It’s also the foundation for other desirable characteristics, like extensibility. Without loose coupling, the job of maintaining your code can quickly grow out of hand.

In this chapter, you’ll see some of the pains of tight coupling and learn how to address them.

10.1. Defining coupling

Because the idea of coupling plays such a big role in effective software development, it’s important to get a solid grip on what it means. What is coupling exactly? You can think of it as the connective tissue between the different areas of your code.

10.1.1. The connective tissue

Coupling can be a tricky concept at first because it’s not necessarily tangible. It’s a kind of mesh that runs throughout your code (figure 10.1). Where two pieces of code have high interdependency, that mesh is tightly woven and taut. Moving either piece of code around requires the other to move around too. The mesh between areas with little or no interdependence is flexible—maybe it’s made of rubber bands. You’d have to change the code in this looser part of the mesh much more drastically for it to impact the code around it.

10.1.2. Tight coupling

10.1.3. Loose coupling

10.2. Recognizing coupling

10.2.1. Feature envy

10.2.2. Shotgun surgery

10.2.3. Leaky abstractions

10.3. Coupling in Bark

10.4. Addressing coupling

10.4.1. User messaging

10.4.2. Bookmark persistence

10.4.3. Try it out