As I understand functions and methods can be used to reduce duplicate coding by calling the said functions or methods by components or procedures. Now, when is it better(uses less system resources) to use duplicate coding than functions\methods or vica versa, i.e if you have 3 or 4 lines of code getting called by 2 or 3 different components is it worth writing a method for than amount of lines? When is it feasible to use one or the other?


6 Years
Discussion Span
Last Post by Krefie

This is a thread?! HAHAHA, I googled for a while and all I got was "Java Coding Standards" telling to use methods to reduce duplicate code

Avoid and remove duplicate code. Put common code into an extra function. Duplicate code may be okay, if otherwise dependencies among so far unrelated modules would be created.

but it doesn't really answer my question regarding system resources...



I would use a common method rather than duplicate 3/4 lines of code (assuming they are non-trivial). Main reason? Maintenance. What happens when you discover that that piece of code needs to be improved or fixed in some way? Now multiply this across a full-sized commercial project.

Edited by JamesCherrill: n/a


... it also makes code MUCH easier to understand, assuming good method names.
Finally, there are a few places where I would avoid the overhead of a method call, but only in the most time-critical, nested loop, intensive processing situations - maybe < 1% of situations - maybe never, depending on the scale of the app.


hmmmm , agreed, for maintenance I would definitely use methods, I just wanted to know if it was worth the effort to write method coding for 3 or 4 lines, and then to get called 2ce maybe 3 times, but your explanation seems sound, I guess I just don't want to go write 40+ methods when copy paste would seem faster ^_^

Fanx Krefie


I use Eclipse, which had a refactoring "thing" that will extract a block of code and turn it into a method for you :-)

But here's good example:

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      window.setLocation((screenSize.width - window.getWidth()) / 2,
            (screenSize.height - window.getHeight()) / 2);

I do this often, so how much better is:


with a short method elsewhere?

And then... what happens when you move to a 2-screen setup? Just one very obvious method to enhance.


lol, i'm to scared to hit the refactor button, or anything close to it...last time I tried that I lost some of my code and I saved ^_^ whooops...but I'll look into it, hopefully Eclipse and Netbeans(which I use) works more or less the same then..

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.