a pretty simple question about inheritance in java:
My abstract super class (only relevant content):
public abstract class Writer {
private final Logger log = LoggerFactory.getLogger(this.getClass());
public Logger getLog() {
return log;
}
}
One of my sub classes:
public class ConcreteWriter extends Writer {
public void write1(){
getLog().error("msg1");
getLog().info("msg2");
getLog().warn("msg3");
getLog().error("msg4");
}
}
As you could see 'getLog()' is repeated each time I need to write a message, and I think that's not "elegant", and maybe it's not efficient as well.
I don't want to break the encapsulation principle of the OO programming, so I reject the use of the access modifier 'protected' in superclass (to use directly "log" variable).
What do you think? It's better to create a new instance of my log in the subclass? or something like this:
public class ConcreteWriter extends Writer {
private final Logger log = getLog();
public void write1(){
log.error("msg1");
log.info("msg2");
log.warn("msg3");
log.error("msg4");
}
}
Having two separate fields which will always have the same value seems like a really bad idea to me. You don't logically have two different pieces of state, so why have two separate fields? Instead, just use a local variable in write1
to avoid the multiple getLog()
calls:
public void write1(){
Logger log = getLog();
log.error("msg1");
log.info("msg2");
log.warn("msg3");
log.error("msg4");
}
For logging specifically, I would tend to have a private static final field per class, and not expose it anywhere else. It's unlikely that you need a different logger per instance, and logging should usually be seen as an implementation detail rather than part of the API, in my opinion.
So I'd have:
public class Writer {
private static final Logger LOG = ...;
// Use LOG when I need to
}
public class ExtendedWriter extends Writer {
private static final Logger LOG = ...;
// Use LOG when I need to
}
See more on this question at Stackoverflow