NodeItem: refactored insertInPath to be easier to understand

This commit is contained in:
Paul Campbell 2016-09-04 19:40:08 +01:00
parent e28b140db8
commit 40f49fd832

View file

@ -1,6 +1,7 @@
package net.kemitix.node; package net.kemitix.node;
import lombok.NonNull; import lombok.NonNull;
import lombok.val;
import java.util.*; import java.util.*;
import java.util.function.Function; import java.util.function.Function;
@ -279,32 +280,40 @@ class NodeItem<T> implements Node<T> {
@Override @Override
public void insertInPath(final Node<T> nodeItem, final String... path) { public void insertInPath(final Node<T> nodeItem, final String... path) {
if (path.length == 0) { if (path.length == 0) {
if (!nodeItem.isNamed()) { insertChild(nodeItem);
// nothing to conflict with } else {
addChild(nodeItem); val item = path[0];
return; findChildByName(item)
} .orElseGet(() -> new NodeItem<>(null, item, this))
String nodeName = nodeItem.getName(); .insertInPath(nodeItem, Arrays.copyOfRange(path, 1, path.length));
final Optional<Node<T>> childNamed = findChildByName(nodeName); }
if (!childNamed.isPresent()) { }
// nothing with the same name exists
addChild(nodeItem); private void insertChild(final Node<T> nodeItem) {
return; if (nodeItem.isNamed()) {
} insertNamedChild(nodeItem);
// we have an existing node with the same name } else {
final Node<T> existing = childNamed.get(); // nothing to conflict with
if (!existing.isEmpty()) { addChild(nodeItem);
throw new NodeException("A non-empty node named '" + nodeName }
+ "' already exists here"); }
} else {
nodeItem.getData().ifPresent(existing::setData); private void insertNamedChild(final Node<T> nodeItem) {
} val childByName = findChildByName(nodeItem.getName());
return; if (childByName.isPresent()) {
// we have an existing node with the same name
val existing = childByName.get();
if (existing.isEmpty()) {
// place any data in the new node into the existing empty node
nodeItem.getData().ifPresent(existing::setData);
} else {
throw new NodeException("A non-empty node named '" + nodeItem.getName()
+ "' already exists here");
}
} else {
// nothing with the same name exists
addChild(nodeItem);
} }
val item = path[0];
findChildByName(item)
.orElseGet(() -> new NodeItem<>(null, item, this))
.insertInPath(nodeItem, Arrays.copyOfRange(path, 1, path.length));
} }
@Override @Override