• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to extract repeated code?  RSS feed

 
David Balažic
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have code like this:



How to not repeat the same catch code every time?
It would be easy with a C like preprocessor, but there is no such thing for Java...

Use a common method which has the exception handling and pass the barX() method via reflection?

Regards,
David
 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
David:

Instead of having bar1() and bar2() methods, why not have a single bar() method, and just pass in a parameter?

John.
 
David Balažic
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John de Michele wrote:David:
Instead of having bar1() and bar2() methods, why not have a single bar() method, and just pass in a parameter?

bar1 , bar2 are not my methods. I don't have control over them.
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Extract the contents of the catch block. If it's a checked exception, if you call the method, you either need to catch it, or declare that the method throws it.
 
David Balažic
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
David Newton wrote:Extract the contents of the catch block.

Can you please tell more? Extract it to where?
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To a new method? Extract Method is one of the most common refactorings.
 
David Balažic
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't see how I could extract the catch code. Care to give an example?
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
David Balažic wrote:I don't see how I could extract the catch code. Care to give an example?

In Eclipse, select the code you want to make into a method and right-click on the selection. Somewhere in the options you will find Extract Method.
 
David Balažic
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Of course.

First I was thinking about extracting the entire catch (and try)part which is impossible.
Extracting only the catch body is of course simple.

Still 3 lines that repeat, but better than nothing.

Thanks!
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could do it using enums:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!