Forums Register Login

How to extract repeated code?

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
David:

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

John.
+Pie Number of slices to send: Send
 

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.
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
 

David Newton wrote:Extract the contents of the catch block.


Can you please tell more? Extract it to where?
+Pie Number of slices to send: Send
To a new method? Extract Method is one of the most common refactorings.
+Pie Number of slices to send: Send
I don't see how I could extract the catch code. Care to give an example?
+Pie Number of slices to send: Send
 

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.
+Pie Number of slices to send: Send
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!
+Pie Number of slices to send: Send
You could do it using enums:
yeah, but ... what would PIE do? Especially concerning this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1074 times.
Similar Threads
how to be able to control if function will throw exception or not
Making an exception!!!
single return statement: yes / no?
Exception handling
difference B/w Throw and throws
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 13:55:34.