Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with cross-cutting concerns in a OO Application? Use Singleton? Dependency Injection? What?

Let's say that I'm currently designing an application where I will need to use a global timing system (it's a cross-cutting concern). I'll need to access data from that global timing system from basically anywhere in my app and it's not like I can see that "this part of the application will need it while the other won't".

My question is.. should I design that as a kind Ambient Context (in this case, Singleton), or should I try to devise other way to accomodate for this?

I certainly don't feel it's correct to make all my classes have to get this global timing class passed to them by constructor injection. Lot's of time I would have to pass the reference really down the chain until some class eventually needs it. On the other hand, it would turn everything more clear from the reading stand point(it makes it clear what my classes' dependencies are).

How do people generally deal with this? Are there any other techniques around that can help with this? AOP maybe?

PS: The global timing system was just an idea I took from a book I'm currently reading. A logging system would be another good example of this kind of problem.

Thanks

like image 367
devoured elysium Avatar asked Aug 19 '10 16:08

devoured elysium


2 Answers

As you suggest, Aspect Oriented Programming (AOP) is designed with just this sort of thing in mind, so I'd certainly check that out.

While constructor injection does seem a hassle in this scenario, using an IOC container might help reduce your pain a bit. A singleton does seem to fit the bill well, but they bring issues with testability due to the staticness - but you can get round this by splitting it into two.

like image 71
Grant Crofton Avatar answered Oct 01 '22 13:10

Grant Crofton


If everybody needs it and it's a one of a kind (just like the log you mentioned), it's definitely a singleton.

like image 21
Michael Clerx Avatar answered Oct 01 '22 14:10

Michael Clerx