So, I’ve looked at some similar questions asked here in regards to how these three should be used in naming. Usually, the answer is something along the lines of “it’s conventional” and “just be consistent”. I’m wondering if that’s the same answer for my question.
I have an interface StatSet
defined as
public interface StatSet {
int getHitpoints();
int getAttack();
int getDefense();
}
I want to define an implementation, where all fields are defined in the constructor:
public final class ReadOnlyStatSet {
public ReadOnlyStatSet(final int hitpoints, final int attack, final int defense) {
this.hitpoints = hitpoints;
this.attack = attack;
this.defense = defense;
}
public int getHitpoints() {
return hitpoints;
}
public int getAttack() {
return attack;
}
public int getDefense() {
return defense;
}
private final int hitpoints;
private final int attack;
private final int defense;
// no other fields
}
My question is: is ReadOnlyStatSet
the best name for this type of class. Or, would Immutable
be more suited. In which grammar would I use one over the other.
3
Any of the above seem logical. Immutable, Unmodifable and ReadOnly all are acceptable choices. It is important however, that you stick to a convention. If some of your classes are ‘Immutable’ while others are ‘ReadOnly’, this could imply that there is a difference, which could confuse a consumer of your public code.
I personally use and prefer Immutable
to describe objects which cannot be mutated, but I also see no reason why anybody who follows a different approach is wrong.
On an aside, I have seen Google’s Guava project use ‘Immutable’, such as in ImmutableSet
, while the Java collections use ‘Unmodifiable’, such as UnmodifiableSet
. The only difference I have been able to discern is that Guava’s ImmutableSet
and friends are their own instances of a collection, while UnmodifiableSet
and friends are wrappers which provide an ‘Unmodifiable’ view of a collection which may change underneath. A consumer of the UnmodifiableSet view cannot change the collection, but someone with a reference to the wrapped collection underneath could change what the UnmodifiableSet contains, so one could very easily argue that the UnmodifiableSet is not ‘immutable.’ This might be why it was not named as ImmutableSet
when it was created.
2
Naming your object immutable/read-only/unmodifiable seems superfluous.
It seems strange to me that you need to use immutable, read-only, unmodifiable or whatever else in the class name if the class already acts as immutable.
That’s something that you should describe using keywords/class structure but not by the name of the class.
2