0

Many methods in my code I am currently working on follows a certain pattern:

public void aMethod(...) throws CustomException {
    Log("aMethod Started")
    try {
        //Many method calls that could throw a CustomException
    } finally {
        Log("aMethod Ended")
    }
}

Changing anything about the CustomException is not an option.

Is there any better alternative that doesn't work with try finally?

  • 1
    What is it about your current pattern that you dislike or want to improve? – khelwood Jan 02 '20 at 09:28
  • 6
    Are you using plain Java? Otherwise, AOP is an option (with Spring for example). – daniu Jan 02 '20 at 09:29
  • It makes it both annoying to work with SonarLint & With every new method I make I have to apply this pattern. – Birgen Vermang Jan 02 '20 at 09:30
  • AOP with Spring as @daniu said or with Interceptors in a J2EE environment – Renato Jan 02 '20 at 09:32
  • Actually, AOP can be used in almost any environment - it just depends on whether you're already using a framework that provides AOP capabilities like Spring or JavaEE/JakartaEE or whether you'd have to add a framework yourself, e.g. AspectJ, Guice, CDI etc. - that being said, AOP is most likely what you want, i.e. add a [cross-cutting concern](https://stackoverflow.com/questions/23700540/cross-cutting-concern-example) like logging. – Thomas Jan 02 '20 at 09:34
  • If you are not comfortable with AOP, then you can create a wrapper function. I have not used Java from long time. This function takes `aMethod` and logs before and after the execution of this function (with try-finally though) – Mangat Rai Modi Jan 02 '20 at 09:45
  • Using AOP is the correct fir for this. please refer this link [https://www.baeldung.com/spring-aop-annotation](https://www.baeldung.com/spring-aop-annotation) – Mandar Dharurkar Jan 02 '20 at 09:41
  • Thank you veryone whoe answered, AOP is indeed the way to go. – Birgen Vermang Jan 02 '20 at 10:02

1 Answers1

2

I would say

finally {
    Log("aMethod Ended")
}

is not good way to log ending of method. If an exception occurred the method has not actually ended but interrupted and returned without completing.

So, the "Log("aMethod Ended")" shall be outside of finally. If end logger is missing in that log, you will anyway get from the exception stack trace.

If you want to just log weather the method was called and then left, then Spring AOP is what could be implemented for the whole product configuration, so you wont need to duplicate the logger everywhere.

On the other hand, if you personally feel this logger wont be of much use and just redundant information; then just turn off that rule in solar lint configuration.