Chapter 6. More use cases in scoping

 

This chapter covers:

  • Customizing scope to suit your needs
  • Avoiding the perils of improper scoping
  • Using advanced scoping: caches and data grids

“A common mistake that people make when trying to design something completely foolproof is to underestimate the ingenuity of complete fools.”

Douglas Adams

As you’ve just seen in chapter 5, scope is a very powerful tool for managing object state. In particular, it is a tool for making your objects and services agnostic of state management. In other words, you allow the injector to worry about the details of state and context, and you keep your objects lean. This has advantages in both productivity and design elegance.

In this chapter we’ll look at how to apply these same principles to any stateful context and to broaden the applicability of scoping as a tool in dependency injection. Most libraries provide some manner of extending the available scoping functionality. We’ll look at how to leverage this in Guice and Spring, in particular.

Closely related are the perils of scoping. While it is extremely powerful as a tool for reversing responsibility, state management can get very tricky to design and build around. We’ll look at common pitfalls and some very hairy corner cases, which one would do well to respect. We’ll also see how good design can ameliorate or completely avoid these cases and how it can also facilitate good testing.

6.1. Defining a custom scope

6.2. Pitfalls and corner cases in scoping

6.3. Leveraging the power of scopes

6.4. Summary