2

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
        }
    }
}
Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79

1 Answers1

1

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 your Collection 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.

TreffnonX
  • 2,924
  • 15
  • 23
  • That sounds like good approach. Is there any concept like `friend` method in Java? – Saurav Sahu Oct 08 '20 at 07:44
  • There is an emulation to that, but it is a bit 'verbose': https://stackoverflow.com/questions/182278/is-there-a-way-to-simulate-the-c-friend-concept-in-java – TreffnonX Oct 08 '20 at 07:46