NodeItem: reduce complexity of addChild

This commit is contained in:
Paul Campbell 2016-09-04 22:13:10 +01:00
parent 9ec2668802
commit 69be86ba07

View file

@ -132,28 +132,34 @@ class NodeItem<T> implements Node<T> {
*/ */
@Override @Override
public void addChild(@NonNull final Node<T> child) { public void addChild(@NonNull final Node<T> child) {
if (this.equals(child) || isDescendantOf(child)) { verifyChildIsNotAnAncestor(child);
throw new NodeException("Child is an ancestor"); verifyChildWithSameNameDoesNotAlreadyExist(child);
}
if (child.isNamed()) {
final Optional<Node<T>> existingChild = findChildByName(
child.getName());
if (existingChild.isPresent() && existingChild.get() != child) {
throw new NodeException(
"Node with that name already exists here");
}
}
children.add(child); children.add(child);
// update the child's parent if they don't have one or it is not this // update the child's parent if they don't have one or it is not this
Optional<Node<T>> childParent = child.getParent(); val childParent = child.getParent();
boolean isOrphan = !childParent.isPresent(); if (!childParent.isPresent() || !childParent.get().equals(this)) {
boolean hasDifferentParent = !isOrphan && !childParent.get()
.equals(this);
if (isOrphan || hasDifferentParent) {
child.setParent(this); child.setParent(this);
} }
} }
private void verifyChildWithSameNameDoesNotAlreadyExist(
final @NonNull Node<T> child) {
if (child.isNamed()) {
findChildByName(child.getName())
.filter(existingChild -> existingChild != child)
.ifPresent(existingChild -> {
throw new NodeException(
"Node with that name already exists here");
});
}
}
private void verifyChildIsNotAnAncestor(final @NonNull Node<T> child) {
if (this.equals(child) || isDescendantOf(child)) {
throw new NodeException("Child is an ancestor");
}
}
/** /**
* Creates a new node and adds it as a child of the current node. * Creates a new node and adds it as a child of the current node.
* *