This article explains a
Set-Once Get-Many (or S.O.G.M. for
short) design pattern. If a class property variable is set once but
has its value getted many times then it makes sense to do the
setting in the constructor and to provide a public getter method
without a public setter method. This design pattern limits how many
times you can set the variable since it can only be done once in the
constructor. This pattern is equally applicable to C++ and Java.
1. The Pattern in Action
Here is an example of this design pattern in operation:
class A
{
private:
int x;
public:
A(int x)
{
this->x = x;
}
void get_x()
{
return x;
}
};
This design pattern translates easily into Java. Converting it to
Java is left as an exercise for you the reader.
2. Limitation of the pattern
This pattern should not be used when there are too many of these
properties, resulting in a constructor call that is error-prone, as
you might erroneously get the order of the arguments to the
constructor wrong. In this case it makes more sense to bring a public
setter method into the class, or more simply (where possible) changing
the privacy status of these properties to public.