aspose file tools*
The moose likes Java in General and the fly likes Reducing duplicate/repetative code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Reducing duplicate/repetative code" Watch "Reducing duplicate/repetative code" New topic
Author

Reducing duplicate/repetative code

Piotr Weglarz
Greenhorn

Joined: Aug 27, 2011
Posts: 3
Greetings!

I was recently given a piece of code by my professor, and asked if I could find a way to reduce/eliminate as much duplicate code as possible and still have it perform the same function. The code in question is actually the code that defines the add method for Binary Search Trees:



Is there anyway to reduce/eliminate the nearly identical code for the left and right sides and still have a fully functioning add method? Keep in mind that my professor didn't specify whether its actually possible to do so, so my options are either a) show an example that works, or b) explain why there's no possible way to do it. Any help would be greatly appreciated, thanks in advance!
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
The given code did not compile. I have added some variables to make it compile. I think the return statements and while(true) can be replaced by using boolean variables. What other redundant code you need to remove?
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
And it leads to redundancy of

Ahh well no idea of doing it
Piotr Weglarz
Greenhorn

Joined: Aug 27, 2011
Posts: 3
My biggest concern was this portion of the code:



As you can see, its nearly identical to:



Is there any way to get rid of rid of this, or should I just assume that its not possible to do?
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8008
    
  22

Piotr Weglarz wrote:Is there any way to get rid of rid of this, or should I just assume that its not possible to do?

Almost anything is possible in programming; the question is: is it a good idea?

In your case, I have a feeling that your prof might be trying to point you towards a recursive solution, where each branch is dealt with by calling the same method again. It's tricky but, especially for things like trees, often produces very elegant solutions.

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reducing duplicate/repetative code