Is it best practices to never alter the contents of a Collection
that is passed as a parameter?
I want orgSet
to only have words. But, sometimes there are one char strings (like question marks, commas, etc.) that I want to remove from the set of words. These are not the full methods, but it makes my point:
public static Set<String> removeSyntax_Foo(Set<String> orgSet) {
Set<String> tmpSet = new HashSet();
for(String s : orgSet) {
if(s.length()!=1) { tmpSet.add(s); }
if(Character.UnicodeBlock.of(s.charAt(0)) == Character.UnicodeBlock.GENERAL_PUNCTUATION) { continue; }
tmpSet.add(s);
}
return tmpSet;
}
public static void removeSyntax_Bar(Set<String> orgSet) {
Set<String> tmpSet = new HashSet();
tmpSet.addAll(orgSet);
orgSet.clear();
for(String s : tmpSet) {
if(s.length()!=1) { orgSet.add(s); }
if(Character.UnicodeBlock.of(s.charAt(0)) == Character.UnicodeBlock.GENERAL_PUNCTUATION) { continue; }
orgSet.add(s);
}
}
removeSyntax_Foo()
has the potential for a careless memory leak. I actually have a list of static methods I use to clean-up my Set
of words. If each of those methods creates a new collection... But, I feel this is the correct solution to use.
removeSyntax_Bar()
jumbles the contents of the invoker's Set
which might be a huge surprise to the invoker. You are not suppose to do that, right?
Is removeSyntax_Foo()
or removeSyntax_Bar()
best practices?