Let's suppose, that we have the following class:
class C
{
private readonly DataType data;
private readonly AdditionalType additional;
C(DataType newData)
{
data = newData;
// LONG code evaluating additional
}
C(OtherType newData)
{
// eval data from newData
// the same LONG code evaluating additional
}
}
Both data
and additional
remain unchanged through the whole life of C. However, there is a code smell: the section evaluating additional
is doubled in both constructors. The natural choice is then to extract it to another method:
class C
{
private readonly DataType data;
private readonly AdditionalType additional;
private void EvalAdditional()
{
// LONG code evaluating additional
}
C(DataType newData)
{
data = newData;
EvalAdditional();
}
C(OtherType newData)
{
// eval data from newData
EvalAdditional();
}
}
But then additional no longer can be readonly (beacuse it is not initialized in ctor).
How to solve this problem in an elegant way?