Chapter 3. Changing the behavior of services

 

Chapter 9 from Object Design Style Guide by Matthias Noback

This chapter covers

  • Changing behavior without changing code
  • Making behaviors configurable and replaceable
  • Introducing abstractions to allow for composition and decoration
  • Avoiding inheritance for overriding object behaviors
  • Making classes final and methods private to prevent object abuse

You can design your services to be created and used in certain ways. But the nature of a software project is that it will change over time. You’ll often modify a class in such a way that, when it’s used, it will behave the way you want it to. However, modifying a class comes with a cost: the danger of breaking it in some way. A common alternative to changing a class is to override some of its methods, but this can cause even more trouble. That’s why, in general, it’s preferable to modify the structure of an object graph instead of the code in a class. It’s better to replace parts than to change them.

9.1. Introduce constructor arguments to make behavior configurable

We’ve discussed earlier how services should be created in one go, with all their dependencies and configuration values provided as constructor arguments. When it comes to changing the behavior of a service object, the constructor is again the place to be. Always prefer using a replaceable constructor argument when you want to influence the behavior of a service.

9.2. Introduce constructor arguments to make behavior replaceable

9.3. Compose abstractions to achieve more complicated behavior

9.4. Decorate existing behavior

9.5. Use notification objects or event listeners for additional behavior

9.6. Don’t use inheritance to change an object’s behavior

9.7. Mark classes as final by default

9.8. Mark methods and properties private by default

Summary

Answers to the exercises