From 69be86ba074ccc8408d87185bf3baeb05bee5d8c Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Sun, 4 Sep 2016 22:13:10 +0100 Subject: [PATCH] NodeItem: reduce complexity of addChild --- src/main/java/net/kemitix/node/NodeItem.java | 38 +++++++++++--------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/src/main/java/net/kemitix/node/NodeItem.java b/src/main/java/net/kemitix/node/NodeItem.java index 979fddd..f9ebf47 100644 --- a/src/main/java/net/kemitix/node/NodeItem.java +++ b/src/main/java/net/kemitix/node/NodeItem.java @@ -132,28 +132,34 @@ class NodeItem implements Node { */ @Override public void addChild(@NonNull final Node child) { - if (this.equals(child) || isDescendantOf(child)) { - throw new NodeException("Child is an ancestor"); - } - if (child.isNamed()) { - final Optional> existingChild = findChildByName( - child.getName()); - if (existingChild.isPresent() && existingChild.get() != child) { - throw new NodeException( - "Node with that name already exists here"); - } - } + verifyChildIsNotAnAncestor(child); + verifyChildWithSameNameDoesNotAlreadyExist(child); children.add(child); // update the child's parent if they don't have one or it is not this - Optional> childParent = child.getParent(); - boolean isOrphan = !childParent.isPresent(); - boolean hasDifferentParent = !isOrphan && !childParent.get() - .equals(this); - if (isOrphan || hasDifferentParent) { + val childParent = child.getParent(); + if (!childParent.isPresent() || !childParent.get().equals(this)) { child.setParent(this); } } + private void verifyChildWithSameNameDoesNotAlreadyExist( + final @NonNull Node 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 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. *