I want to restrict or limit update to members palidromes
and palidromesFIFO
to only one method, say addPalindromeWord
, and don't let any other methods to update it. Is there a way to do that?
Target is to achieve modularity in handling the addition of any new value to the collections. Some basic logic has to be followed. I would not like to see any other method DIRECTLY affecting the collections in abstract manner.
static class MyPalindromes{
private Set<String> palidromes;
private Deque<String> palidromesFIFO;
private int maxLenOfCache;
public MyPalindromes(int maxCachingLength) {
palidromes = new TreeSet<>(new MyComparator());
palidromesFIFO = new ArrayDeque<String>();
maxLenOfCache = maxCachingLength;
}
public void addPalindromeWord(String word) {
palidromes.add(word);
if (palidromesFIFO.size() == maxLenOfCache && !palidromesFIFO.isEmpty()) {
palidromesFIFO.removeFirst();
}
if (maxLenOfCache > 0) {
palidromesFIFO.addLast(word);
}
}
public void filterAndAddOnlyPalindromes(List<String> words) {
List<String> validWords = new ArrayList<>();
for (String w : words) {
if (isPalindrome(w)) {
validWords.add(w);
}
}
this.addPalindromeWords(validWords);
}
public void addPalindromeWords(List<String> words) {
for (String word : words) {
// palidromes.add(validWords); //<< DISALLOW this direct update to the set
this.addPalindromeWord(word); // << ONLY allow update through addPalindromeWord method
}
}
}
You can 'nest' your collection in a dedicated (optionally inner)
class
that only has these methods public. Then the outer class cannot access the private fields and methods, and yourCollection
is save from modification in other ways.You must however also ensure, that the
Collection
is not returned, otherwise developers could modify it directly. Do this by delegating any purely reading operations from the collection in the inner class.If you do this 'generic enough', you only need a bunch of classes to handle this. It's actually a nice thing to build a tiny library around.