javacode-standards

Java common Try/Finally block around different code blocks - code style


I have the same if() { try { < SOME CODE > } finally { } } else {} block that I use in 3 methods.

The only thing that's different in each method is < SOME CODE >.

Are there any coding patterns that I can use to "DRY" my code? Ideally would like to extract the if() { try { } finally { } } else {} to some common structure and pass the < SOME CODE > to it. Is that possible in Java?

Thanks


Solution

  • You could introduce a common method to factor out the common part.

    Then according to your requirements you could do :

    1) if the 3 methods are in the same class : extracting each set of statements of the try bodies in 3 specific methods and pass this method as a Runnable parameter in the common method.
    For example :

    public void commonMethod(Runnable methodToInvoke){
    
         if() {
                try { methodToInvoke.run() } finally { } 
         } 
         else {}
    }
    

    And call it by passing the 3 extracted methods :

    commonMethod(this::methodFoo);
    commonMethod(this::methodBar);
    commonMethod(this::methodFooBar);
    

    2) if the 3 methods are in distinct classes : introducing an interface that the 3 classes will implement and make the common method accept a parameter of this interface.

    For example with a Processing interface introduced :

    public void commonMethod(Processing processing){
    
         if() {
                try { processing.doThat() } finally { } 
         } 
         else {}
    }
    

    And call it by passing the 3 implementations of the Processing interface :

    commonMethod(foo);
    commonMethod(bar);
    commonMethod(fooBar);