samedi 15 décembre 2018

Java question on runtime type checking in implemented method

I am designing some java objects to represent graphs and trees. For my use case I will be using both data types but I also want my graph algorithms to work on my trees.

import java.util.List;

public interface Node<T> {
    T getValue();
    List<? extends Node<T>> getNeighbors();
    void addNodes(List<? extends Node<T>> nodes);
}

public interface TreeNode<T> extends Node<T> {
    List<? extends TreeNode<T>> getChildren();
    void addChildren(List<? extends TreeNode<T>> treeNodes);

    @Override
    default List<? extends Node<T>> getNeighbors() {
        return getChildren();
    }

    @Override
    default void addNodes(List<? extends Node<T>> nodes) {
        if(nodes.getClass().isInstance(getChildren().getClass())) {
            addChildren((List<? extends TreeNode<T>>) nodes);
        } else {
            throw new RuntimeException("Type error!");
        }
    }
}

My question is about how I'm dealing with addNodes method in the Node interface in the TreeNode interface. The addNodes method has to be in the Node interface because I want to allow people to write code that can add nodes to graphs. However, I also don't want people to add arbitrary nodes to a tree node(for example adding a graph node to a tree node).

In order to prevent this, I'm checking the type of nodes at runtime and throwing an exception if the type is not right. I'm just wondering if this is the best way to accomplish what I want or if there is a better practice?

Thanks for helping :)

Aucun commentaire:

Enregistrer un commentaire