Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reducing duplicate/repetative code

 
Piotr Weglarz
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And it leads to redundancy of

Ahh well no idea of doing it
 
Piotr Weglarz
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 10417
63
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic