Chapter 8. Managing an object’s behavior
This chapter covers:
- Intercepting methods with AOP
- Using transactions, security, and the like
- Watching for perils of proxying
- Avoiding corner cases
“Perfect behavior is born of complete indifference.”
Cesare Pavese
Often one finds that certain types of logic are repeated throughout a program. Many separate parts of an application share similar concerns such as logging, security, or transactions. These are known as crosscutting concerns.
Rather than address these concerns in each individual class (as one would do normally), it’s easier to address them all at once from a central location. Not only does this reduce repetitive boilerplate code, but it also makes maintenance of existing code less complicated.
Let’s look at an example. Brokerage is a class that places an order for stock inside a database transaction. Traditionally, we would write code for starting and ending a transaction around each business method:
This transaction logic uses a TransactionManager to start and end a transaction, rolling back on an exception or committing as appropriate. This would be repeated in every method that needed to be transactional.
Now let’s look at this if transactions were described declaratively: