-
Good design?
Is the below design OK?
Code:
public abstract class MyAbstract
{
public Dictionary<int, ushort> Table
{
get;
protected set;
}
protected MyAbstract()
{
PopulateTable();
}
protected abstract void PopulateTable();
}
Table will be initialized inside PopulateTable() by it's derived classes;
-
Re: Good design?
Calling virtual (or abstract) methods in a constructor is generally not a good idea as it will 'break' any initialisation of member variables which a subclass performs.
If someone subclasses 'MyAbstract' and initialises variables in their constructor which they rely on in their implementation of PopulateTable - those variables will be null when PopulateTable is called. The easiest way to work around this issue is to only create instances of MyAbstract through a factory so you can do something like:
Code:
public T Create <T> () where T : MyAbstract, new ()
{
T instance = new T ();
instance.PopulateTable ();
return instance;
}
-
Re: Good design?
Thanks, that makes sense.
I have now modified to:
Code:
public abstract class MyAbstract
{
public abstract Dictionary<int, ushort> Table { get; }
}
And I think the above code doesn't bring big difference to interface