A safer way to return a generic indicator object indicating failure

Posted on

Problem

I’m writing a singly-linked list that implements the List interface. I decided going in that I’d try to implement every method as an exercise; even the optional ones.

I started writing the ListIterator, and found the need to return the node previous to a given node for operations like add. Unfortunately, I didn’t anticipate this scenario prior to writing the rest of the list, and have no way of indicating failure (failure being that the given node doesn’t exist in the list), since null is a valid return if the root node is supplied. I decided to allow the caller to pass in an indicator node that would be returned if the node wasn’t found. I wasn’t sure the best way to handle this thought, since Node is generic.

I ended up making the indicator of type Node<Object>, and casting it prior to returning. I know this is dangerous though, so I made it very clear in the documentation that the method isn’t safe (plus, of course, it’s private).

I’d like to know if there’s a less hack-ish way of dealing with this scenario though.

I didn’t think including the full implementation was necessary. The names should be obvious enough (I hope).

/**
 * Dangerous.
 * Returns the node that comes before the given node, or badNode if the
 *  node doesn't exist in the list.
 * The return must be checked against badNode prior to use!
 *  
 * @param node The node to find the predecessor of 
 * @param badNode The indicator that will be returned if node isn't in the list
 * @return The predecessor of node, or badNode if node doesn't exist.
 */
@SuppressWarnings("unchecked")
private Node<E> getNodeBefore(Node<E> node, Node<Object> badNode) {
    Node<E> curNode = getRootNode();
    Node<E> prevNode = null;

    while (curNode != null) {
        if (curNode == node) {
            return prevNode;
        }

    prevNode = curNode;
    curNode = curNode.getNextNode();
    }

    return (Node<E>)badNode;
}

Solution

A fairly clean way is to use Optionals, like these or those. So you would make getNodeBefore return an Optional<Node<E>>.

The badNode idea is, hm, exotic to me.

Leave a Reply

Your email address will not be published. Required fields are marked *