views:

104

answers:

3

Here's my problem:

If need to implement a B-Tree for University:

I have an "outer" class B-Tree with attributes root and _degree. The class to represent the nodes is implemented as a static-member class:

public class BTree<E> {
    private Node<E> root;
    // the minimal degree
    private int degree;

    public BTree(int degree) {
        if (degree < 2) {
            throw new IllegalArgumentException();
        }

        this.degree = degree;
    }

    // other stuff

    private static class Node<T> {
        T[] elements       = (T[])new Object[degree * 2 - 1];
        Node<T>[] children = (Node<T>[])new Object[degree * 2];
        int size           = 0;
    }
}

So, now my problem is: As I implemented the Node class as a static member class, I can't access the degree attribute of the outer class.

Now I have to choices:

  1. Make the Node class an inner class (non-static member class) OR
  2. Create a constructor for the Node class and pass the degree in every time I need to construct a Node.

What would be the best choice? Making it an inner class would mean the Nodes would all have a reference to the Btree (outer class), but making it a static member class would mean I would have to pass the degree in every time.

+4  A: 

I would keep it static and pass degree in. That way you ensure that Node cannot know any details about BTree.

Justin Ethier
+1  A: 

If it were me, I'd have the Node class public so I could reuse it in other containing data structures, but that's just me. In that case, I'd have to pass the degree through the constructor, and that's OK with me too. I don't like the idea of inner classes manipulating the members of enclosing classes. I feel it makes the classes too tightly bound to each other. I know sometimes it's appropriate, but I avoid when I can and this seems an easily avoidable case.

FrustratedWithFormsDesigner
+1  A: 

There are arguments to make it static, because it decouples the classes.

But I think a BTree.Node is a node from a particular BTree. It doesn't make sense to go and create a bunch of Nodes (with random degrees). You can't have a Node, but no Tree. Thus, I say non-static.

Ishtar