Last week, we had the author of TDD for a Shopping Website LiveProject. Friday at 11am Ranch time, Steven Solomon will be hosting a live TDD session just for us. See for the agenda and registration link
Well, I wouldn't normally write code in which the constructor of a class sets a static variable like that. But apart from that, if the code does what you want it to do then there's nothing wrong with it.
I wouldn't implement like that. It will probably work if you only have one class extending your abstract class B but as soon as you introduce another class you will get confusing results.
The logger will always be linked to the latest instance created. Try the following code. It is unlikely to give your desired results.
btw you test method could throw a nasty NullPointerException. You've declared it static so you don't need an instance of the class but the logger attribute will only be created after you have created an instance of a B.
How about this:
The logger gets created once the class is loaded, and can never change. It also takes away the confusion that Paul's class described - the logger is always using class B for logging.
Paul Beckett wrote:btw you test method could throw a nasty NullPointerException. You've declared it static so you don't need an instance of the class but the logger attribute will only be created after you have created an instance of a B.
Hi Paul, your points are valid. Guess I'll stick to instantiate the logger using the private modifier. Thanks!
Rob Prime wrote:How about this:
The logger gets created once the class is loaded, and can never change. It also takes away the confusion that Paul's class described - the logger is always using class B for logging.
Hi Rob, what about class C? By doing that you are only instantiating the logger with class B as the parameter.
If you want each class to have its own logger, then you have two options:
1) make the logger an instance field, not a static field. Each instance has its own logger. You will need instances to log though
2) give each class its own static logger; don't use B's logger in class C at all
As said before by Paul, if you share the logger field among all classes, then C will change B's logger, so B will start logging for class C. That's definitely not what you want.