19.10 Categories and DSLs
Using categories, we can intercept method calls in a controlled fashion (see Section 13.1, Injecting Methods Using Categories). We can put that to use in creating a DSL. Let’s figure out ways to implement the following fluent call: 2.days.ago.at(4.30).
2 is an instance of Integer, and we know that days is not a property on it. We’ll inject that, using categories, as a property (the
getDays
method). The days is just noise here, but in another context it may be useful to differentiate between five days ago and five minutes ago. It provides connectivity in the sentence “two days ago at 4.30.” We can implement the method
getDays
that accepts Integer and returns the received instance. In the
getAgo
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access