Reputation: 77
I'm confused about when to make a Java class a:
For example
class School {
static class Grade {
static class Class {
static class Student {
}
}
}
}
Is this a logically good design? It puts objects in logical layers. If classes aren't nested in this way, the logical layers pollute the namespace. A student may go elsewhere. Would creating a package for Student make it better?
Should this structure be nested or flattened?
Upvotes: 0
Views: 1859
Reputation: 19895
Nested static classes are generally good when you want to "hide" their code from other classes, or when you want to associate that code with the enclosing class.
They are not commonly used for multi-level encapsulation as in your example, or when they are fairly large (say, over 100-200 lines), because they become difficult to maintain. In such cases, you should better use packages.
A nice overview of the 2 types of nested classes (static and non-static, aka inner) can be found in an earlier StackOverflow question, as well as in the Nested Classes section of the Java Tutorial
.
Upvotes: 0
Reputation: 25623
Flatten. This looks a little like you've have conflated the ideas of instance encapsulation with namespaces. A School instance may contain many references to Students, but there is no reason why the Student type should be scoped within the School type.
Student may mean student clothes else where.
Student should never mean anything other than student. It should not have nothing to do with clothes.
If we create a package for them, it'll be a little better.
Yes, packages are containers for organizing types. Types themselves should not be used in this way unless a nested type:
Is so tightly coupled with the outer type that it would be meaningless on its own.
Is a common concept manifested in a way that is specific to the outer class. For example, Map.Entry
is appropriate as a nested, static type (interface) because 'entry' is such a general concept, and this particular type of entry is only relevant when dealing with maps.
Is only used within its outer class and is not visible outside of it (or at least not visible outside of the package).
Upvotes: 1
Reputation: 68847
In my opinion: Flatten. Because Students don't remain for ever in the same class.
Upvotes: 2