czwartek, 22 stycznia 2015

Cross Cutting Concerns

A programmer writes code to query his database. He uses the log function over and over again. Then you get to the UI and use the same logger. You end up with using the same class cross cutting through all of your app modules.

You can think of many concerns that'll cut your app like caching, analytics, security. Why are Cross Cutting Concerns bad ?

  • Single Responsibility Principle is violated. Example: You have a network module that also logs, secures, sends analytics etc.
  • It breaks the modularity of your app.
  • It makes the code practically not reusable. Business logic should be separated from implementation code.

Decorator Pattern

How do we fix this ? There has to be some pattern, right ? Well, there is. You can  use the Decorator pattern to decorate the operation with all the concerns.

Here's a lengthy post about having abstracted commands, that can be decorated.

Of course, there's a drawback to all that: a lot of abstractions. Of course, abstracting your modules in your code is good, but this forces you to abstract every little action you want to log (for example). You can end up with hundreds of interfaces, just for the sake of removing cross cutting concerns. Quite costly, huh ? There has to be a better way.

Aspect Oriented Programming

Wikipedia for Aspect Oriented Programming might look a little scary, but it can be as simple as that: you set up blocks of code to be executed before, or after a certain method in a certain class. 

The Aspects library for Objective-C uses method swizzling to achieve that. Very clean, doesn't need additional classes/abstractions, it isolates your concerns.