Chapter 8. Dynamic programming with Groovy

 

This chapter covers

  • How Groovy supports dynamic programming
  • An explanation of the Meta Object Protocol (MOP)
  • How to utilize the MOP for your own purposes

Until real software engineering is developed, the next best practice is to develop with a dynamic system that has extreme late binding in all aspects.

Alan Kay

We’re going to start our journey with a few general considerations about dynamic programming, how it differs from conventional object-oriented approaches, and why you want to have it in your toolbox. We’ll show how the MOP serves as the central hub that provides you with dynamic programming capabilities. Groovy comes with dynamic features out-of-the-box but you can also add your own. There are various ways of achieving this and we’ll start with the simpler ones and slowly move on to the more advanced use cases. As you’ll see, there’s no reason to be scared about words like “dynamic” or “meta.” If by the end of this chapter you say, “Well, it isn’t so magical after all,” then we’ve achieved our goal.

If you seek perfection in completeness, designing and implementing an object-oriented system becomes hard. It may well be impossible.

Imagine you’re responsible for java.lang.Integer. You’re of course aware that this class will be used for counting, indexing, calculations, and so on, but you cannot possibly anticipate all use cases.

8.1. What is dynamic programming?

8.2. Meta Object Protocol

8.3. Customizing the MOP with hook methods

8.4. Modifying behavior through the metaclass

8.5. Real-world dynamic programming in action

8.6. Summary