0

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

John Fitch
  • 113
  • 1
  • 6
  • Maybe it is possible. I don't think it is worth the effort. You will need to change the code in the `finally` block based on the resources used in the `try` block. What if various `try` blocks throw different exceptions? How are you going to catch them? – jrook Oct 12 '18 at 17:16
  • not planning to handle any exceptions in that block of the code. Instead I would expect exceptions to be thrown up. Finally {} block is important as that's where I am doing some cleanup. – John Fitch Oct 12 '18 at 17:32

1 Answers1

1

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);
davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • The 3 methods are indeed in the same class. In fact this is a Spring Controller class that has the 3 methods that handle UI actions. With introduction of `Runnable` I will be effectively kicking off separate thread for each call to the method, which could lead to undesirable results. – John Fitch Oct 12 '18 at 17:36
  • @JohnFitch the fact that you call `Runnable.run` somewhere in your code doesn't mean that you start a new thread. To spawn new thread you either need to create `Thread` object explicitly or submit `Runnable` to thread pool. – Ivan Oct 12 '18 at 17:37
  • 1
    Ivan is right. I used the `Runnable` interface as its functional descriptor matches perfectly to invoke a method : the `run()` method takes no arg and is `void`. So yes you don't need and don't have to introduce threads if your actual code didn't need them. – davidxxx Oct 12 '18 at 18:33