-1

In my data structures class, we are implementing the Nodes of a red/black tree using a private inner class. This kind of Node is unique to red/black trees, so the inner class's visibility is private. The members of an inner class are always accessible from the enclosing class.

How should I choose a visibility for the members of this inner class? If there is no difference to the compiler, which visibility would make the most sense semantically?

public class RedBlackTree<K extends Comparable<? super K>, V> {

    private static enum NodeColor { RED, BLACK }

    private class Node {
        private final K key; // these are private, currently for no particular reason
        private V value;
        private Node left;
        private Node right;
        private NodeColor color;

        private Node(K key, V value, NodeColor color) {
            this.key = key;
            this.value = value;
            this.color = color;
        }
    }

    // Precondition - both children are red, and node is black.
    // Postcondition - both children are black, and node is red.
    private void colorFlip(Node node) {
        node.color = NodeColor.RED;
        node.left.color = NodeColor.BLACK; // these statements compile, as expected
        node.right.color = NodeColor.BLACK;
    }

}

In this question, the OP said private made sense semantically, while in this answer, the author said public made sense semantically. Which one is best practice, if any?

Community
  • 1
  • 1
4castle
  • 32,613
  • 11
  • 69
  • 106

1 Answers1

1

In the end, this depends on your coding style. For myself, I tend to view private as "within this class only", even if outer classes can use them, so I declare variables that are only used in the inner class as private. Unlike many other devs, I imagine, I make everything else default (no modifier).

Using public for "non-private" members is probably a better idea though, to be honest, as others who view your code will know that it is your intention to have that member used outside of the inner class.

As long as you aren't tempted to write unnecessary or inefficient code (such as getters/setters for your private fields of your private inner class), you can follow whatever paradigm you like. If you're working with others or within a group project, try to follow the current trend.

Zircon
  • 4,677
  • 15
  • 32
  • I agree with this semantic meaning of `private`. It says something about where the encapsulation begins and ends for a member. Some conflicting practices I can see are "always use the narrowest possible visibility" or "keep all non-final members hidden", but the Java language doesn't seem to protect the encapsulation of inner classes, so I might as well make up for that by being explicit with `public`. – 4castle Oct 11 '16 at 20:20