Skip to main content
2 of 4
added 1498 characters in body
Spotted
  • 1.7k
  • 10
  • 18

I have the feeling that you absolutly want to use a pattern. Be warned that using a design pattern doesn't always result in a better code ! Remember that design patterns must serve the developper and not the opposite.

Your case is tricky as it seems you want to do 2 kinds of logging:

  1. Logging some steps of your logical functionality (inside execute)
  2. Logging around function calls (entering/exiting a function) (outside execute)

For the first case, at the moment you want to log some things inside a function, you have to do it... inside the function. You could use the template method pattern to make things a bit prettier but I think it's overkill in this case.

public final class MyBusinessFunction extends BaseFunction {
    @Override
    public final void execute() {
        log.info("Initializing some variables");
        int i = 0;
        double d = 1.0;
        
        log.info("Starting algorithm");
        for(...) {
            ...
            log.info("One step forward");
            ...
        }
        log.info("Ending algorithm");

        ...
        log.info("Cleaning some mess");
        ...
    }
}

For the second case, the decorator pattern is the way to go:

public final class LoggingFunction extends BaseFunction {
    private final BaseFunction origin;

    public LoggingFunction(BaseFunction origin) {
        this.origin = origin;
    }

    @Override
    public final void execute() {
        log.info("Entering execute");
        origin.execute();
        log.info("Exiting execute");
    }
}

And you could use it like this in BusinessClass:

public final BusinessClass {
    private final BaseFunction f1;

    public BusinessClass() {
        this.f1 = new LoggingFunction(new MyBusinessFunction());
    }

    public final void doFunction() {
        f1.execute();
    }
}

A call to doFunction will log this:

Entering function
Initializing some variables
Starting algorithm
One step forward
One step forward
...
Ending algorithm
Cleaning some mess
Exiting function
Spotted
  • 1.7k
  • 10
  • 18