java - Separate logic from logging via template method pattern -


may use template method pattern separate logic logging , exception handling or "bad practice"?

for example have code:

public abstract class parent {     private final logger log = loggerfactory.getlogger(getclass());  public void eat() {     try {         doeat();     } catch (someexception1 e) {         log.debug("some text");         throw new customexception1();     } }  protected abstract void doeat();  public void sleep() {     try {         dosleep();     } catch (someexception2 e) {         log.debug("some text");         throw new customexception2();     } }  protected abstract void dosleep(); } 

and child class:

public class child extends parent { @override protected void doeat() {     //some logic }  @override protected void dosleep() {     //some logic }} 

i not have different implementations of methods doeat() , dosleep().

i want know whether it's worth , 'bad practice' or not.

if pattern solves problem having, , confident won't cause more problems later, don't see issue.

my personal preference here decorator pattern. in "template" version, child extends parent, logging behaviour isn't separate logic, it's hidden. benefit it's reusable in multiple subtypes of parent. them separate mean change either of them, independently, without client needing know. how "decorator" version might work:

public class thing implements mybehaviour {     @override     public void eat() {         //some logic     } } 

then, logging:

public class loggingthing implements mybehaviour {     public mybehaviour delegate;      public loggingthing(mybehaviour delegate) {         this.delegate = delegate;     }      @override     public void eat() {         try {             delegate.eat();         } catch (myexception e) {             // behaviour         }     } } 

now logging behaviour separate "eat" behaviour. can have mybehaviour logs, can have mybehaviour doesn't log, , can have mybehaviour other thing want do. client never needs know 1 has.

prefer association on inheritance.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -