I have a big repository of data, thousands of objects. Here's a simplified interface:
public interface Score {
public Float getValue();
public void setValue(Float newValue);
}
Now, the big repository holds these objects in indexes for fast retrieval, so it's important that setValue
not be called outside of the repository context. In fact, I don't want clients of the repository to change any part of the score objects.
At first I thought that I should return copies of the Score
s, but that would get pretty expensive - the data is queried often. My next idea is making an UnmodifiableScore
interface:
public interface UnmodifiableScore {
public Float getValue();
}
public interface Score extends UnmodifiableScore {
public void setValue(Float newValue);
}
Then, my repository could return UnmodifiableScore
s.
Clearly, clients to the code could cast down to Score
s and change values at their will. It would still be possible to change the values in the central repository and break the whole thing. But it would save a LOT of copying.
I think for our purposes, the naming convention will be enough to remind us not to modify the scores. If we release code as a library, though, I'm not as confident. Is there some way to make it so that only a few privileged classes can see the read/write interface? This central repository needs it, and my server needs it (two different packages), but everyone else can make do with the read-only interface. Is there any clever way to do this? Any analog of friend
from C++?