views:

77

answers:

4

I have a Logging class which gets instantiated on startup of a console app and the stored in a static variable.

If i want a class to use the logger should it be passed to the class in the constructor or referenced directly?

I'm trying to write unit tests and either way i should be able to do it. Just means i have to set the static variable before calling the code that uses it.

Cheers.

A: 

To make your classes as unit testable as possible, all dependencies, including loggers, should be passed in whenever possible. This is what is called Dependency Injection (DI), and is a very common and standard pattern for writing unit testable code. Logging is almost always a cross-cutting concern that is only embedded within the bodies of methods because there aren't really any decent AOP frameworks to properly pull those concerns out and apply them declaratively. Having to deal with logging when writing/running unit tests just increases the complexity of the tests, possibly adding additional configuration concerns, when you really want to keep your tests as simple and targeted as possible.

jrista
I agree however it means that every class that needs logging needs to pass an instance of the logger to it. Is this going to get too busy?
Schotime
A: 

How about using the Static Gateway Pattern ?

AB Kolan
hmmm.. downvote.. curious .. why ?
AB Kolan
A: 

You could create an instance of it and store that instance as a member of the same class & return that via a property.

e.g. Logger.Default
This will return the reference to the instance that was created.

EDIT: An example of this could be Console class & it's SetOut method. I mean you can keep on using Console.WriteLine.... and if you want to change the stream, use the SetOut method. It redirects the output to a new stream.

Hope that helps.

shahkalpesh
shahkalpesh
Explaining a downvote isn't really part of this site's DNA, but it probably isn't significant here anyway. Every answer here (save perhaps one) was downvoted in a very short timeframe.
Shmoopty
Site shouldn't have DNA. But people should have the DNA of courtesy ;)
shahkalpesh
Well, you're back to zero, as your answer seems fine to me.
Shmoopty
Haha. Thanks Shmoopty.
shahkalpesh
+1  A: 

Sounds like what you're looking for is some sort of IoC container. You could use EntLib's Unity or something else like that.

Esteban Araya