Java – how to refactor if else bodies that perform similar operations?
I have to write a class for the node of the binary tree in Java, not just the method. There is almost the same problem as the body of the if else statement 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, I want to find a way to avoid code duplication The only solution I proposed was to work in C, but not in Java This creates a "left" or "right" reference instead of using it for allocation
To imagine 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 to lead and follow!! Because the way reference semantics work in Java doesn't work As mentioned earlier, in C, I just create a reference on the left or right reference and process it
Is there any way to write this code in Java without using duplicate code? Maybe I will encounter this problem again in more complex situations. I want to solve it now, because with all due respect, it brings better maintainable code
Solution
I created a reusable private method to isolate duplicate logic:
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 said, this particular example is quite small, but this pattern is also useful here. Of course, when the isolated / decomposed logic is more complex
If you are worried about the cost of method calls, do not do so Method calls are really cheap.: -) If this is a hot spot in the code, modern JVMs (such as Oracle) will recognize it and inline method calls, if it is advantageous to do so