evolve75/RubyTree

TreeNode#add side effect leads to inconsistency

MMF2 opened this issue · 3 comments

MMF2 commented

If a TreeNode n with parent p within a tree t1 is added as a child of p' within another tree t2, then n remains a child of p within t1 but inconsistently reports its parent to be p' (by calling TreeNode#parent).

I suggest to change behavior in one of the following two ways:
Change possibility 1: Adding n to p' gets a 'move' semantics, i.e. n is removed from p by adding n to p'.
Change possibility 2: Duplicate n, then add the copy to p' and leave t1 untouched.

Example:
t1 = Tree::TreeNode.new('1')
t1 << Tree::TreeNode.new('2') << Tree::TreeNode.new('4')
t1 << Tree::TreeNode.new('3') << Tree::TreeNode.new('5')
t['3'] << Tree::TreeNode.new('6')

t2 = t1.dup

t2['3'] << t1['2']['4']

t1['2']['4'].parent.name # => '3' !

MMF2 commented

Sorry bug in code example:
It is
t1['3'] << Tree::TreeNode.new('6')
not
t['3'] << Tree::TreeNode.new('6')

Thanks for identifying this. Will check and update in the master branch shortly.

@MMF2,

The issue has been fixed in commit d3b2bf0 (release 0.9.5pre5). I will be releasing the gem this week.