3 ms·
Making a class immutable doesn't mean that the implementation is fixed. If you need to change your implementation to store data differently, the consumers of yo
by organsnyder 12y ago
Making a class immutable doesn't mean that the implementation is fixed. If you need to change your implementation to store data differently, the consumers of your API shouldn't need to be modified. The following modification to your first class would still be immutable:
public class Article {
private final Author author;
...
public String getAuthor() {
return author.getName();
}
}
Also, your first class isn't fully immutable—getTags should be implemented as follows:
/**
* @return Unmodifiable list of tags
*/
public List<String> getTags() {
return Collections.unmodifiableList(tags);
}
- Proleps 12y ago> Also, your first class isn't fully immutable—getTags should be implemented as follows: True. It would be nice if Java had some immutable collection classes that don't have mutable methods. A method that gets a List<String> made with Collections.unmodifiableList(tags), doesn't know that it is actually immutable.