I want to make my class immutable. Obvious way would be to declare all fields as get; private set; and to initialize all fields in constructor. So clients must provide everything in constructor. The problem is that when there are ~10 or more fields passing them in constructor become very unreadable, because there are no labels for each field.
For example this is pretty readable:
info = new StockInfo
{
Name = data[0] as string,
Status = s,
LotSize = (int)data[1],
ISIN = data[2] as string,
MinStep = (decimal)data[3]
};
compare to this:
new StockInfo(data[0] as string, s, (int) data[1], data[2] as string, (decimal) data[3])
And now imaging that I have 10 or more parameters.
So how can I make class immutable saving readability?
I can suggest only use the same formatting when using constructor:
info = new StockInfo(
data[0] as string, // Name
s, // Status
(int)data[1], // LotSize
data[2] as string, // ISIN
(decimal)data[3] // MinStep
);
Can you suggest something better?
No, it is not possible. Either you have immutable object or you want to have ability to modify object.
Looking at your code I may also suggest that you extract parameters first, so instead of passing something like
data[0] as stringyou usestring stockName = data[0] as string;and then usestockName. That should make your code more readable.If you’re passing so many parameters to the constructor of your object it may be a good idea to revise your design. You may be violating Single Responsibility principle.