Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refactor if-else bodies which perform similar action?

Tags:

java

I had to program a class for binary trees' nodes in java, and more than method had the problem that the bodies of an if-else statement did pretty much the same thing. For example:

public void insert(int val) {
    if(val < key)
        if(left == null)
            left = new TreeNode(val, this);
        else
            left.insert(val);
    else
        if(right == null)
            right = new TreeNode(val, this);
        else
            right.insert(val);
}

Here code is repeated and I'd like to find a way to avoid this code repetition. The only solution I've come up with, would work in C++, but not in java. That would be creating a reference on either 'left' or 'right' and than using that reference for the assignments.

To visualize it, something in the style:

public void insert(int val) {
    TreeNode direction = right;
    if(val < key)
        direction = left;

    if(direction == null)
 !!     direction = new TreeNode(val, this);  !!
    else
        direction.insert(val);
}

Where the line with leading and trailing !! wouldn't work because of the way reference semantics works in java. As said before, in C++, I'd simply create a reference on the left or right reference and work on that.

Is there any way to write this code in java without using the repetition of code? Probably I'll encounter this problem again, in more complex situations, and I'd like to now how to solve it, since IMHO it brings to better maintainable code.

like image 932
Sven Avatar asked Jan 22 '26 14:01

Sven


1 Answers

I'd create a reusable private method to isolate the logic that's repeated:

private TreeNode handleNode(TreeNode node, int val) {
    if(node == null)
        node = new TreeNode(val, this);
    else
        node.insert(val);
    return node;
}

then

public void insert(int val) {
    if(val < key)
        left = handleNode(left, val);
    else
        right = handleNode(right, val);
}

As you say, this particular example is fairly minimal, but this pattern is useful even here, and certainly when the logic being isolated/factored out is more complex.

If you're worried about the overhead of a method call, don't be. Method calls are really, really cheap. :-) And if this were a hotspot in the code, a modern JVM (like Oracle's) would identify that and inline the method call anyway, if it would be beneficial to do so.

like image 146
T.J. Crowder Avatar answered Jan 25 '26 04:01

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!