I get the general idea of encapsulation in object oriented programming and how it facilitates later code modifications. However I often get confused how far should the isolation of objects go, especially in terms of construction of related objects.
My question is how much should two classes of one package know about themselves, both having package visibility, related in a way that one class is to return the other one. For example consider class A and class B, where B is some limited view to A, however not necessarily containing the same type of Collection internally.
Consider a practical example, implementing a board game like chess or checkers.
Let the board be implemented as a bulk of Paths i.e. a collections of references to Fields that can be a subject of legal movement, from one board edge to the other one.
Let Vector be an object that has partial access to that Path, however only to the extent defined by the two Field indexes. Consider subList method analogy.
Such Vector is given to the Figure object (e.g. Pawn) that exercises movement and uses that structure to gain information if the movement is possible and to execute movement through methods implementing Figure replacement and Figure captures.
To get Vector, Board method is executed that gets appropriate Path and it in turns is to return the Vector. It is the only way to get an Vector object.
The question here is how and where should Vector be constructed? There are few scenarios here:
Can Path pass whole reference to
fields
field to Vector constructor or would that be a breach of encapsulation?Should
getVector
method construct propercontainer
first and just then should it be passed to some dead simpleVector
constructor?Or maybe should I put fields to some intermediary Collection not related to any of the two classes' implementations?
Here is some code in Java for illustration:
class Path {
private LinkedList<Field> fields;
public Vector getVector(FieldIndex start, FieldIndex end) {
/** ... */
}
}
class Vector {
/** some internal hidden representation */
private SomeContainer<Field> container;
/** some public methods for querying the fields contained */
}
fileds
and container
can be very much different depending on implementation. For example fields
can hold all fields associated with a given Board path, but container
could hold, say, only occupied fields. The point is to design relations between objects to rely very little on internals.