I have a simple basic question about C# and inheritance.
In the below example, I’m showing 2 ways of setting a must set properties (CaptionDisplayText and Firstname):
public abstract class BaseClass
{
private string _firstName;
protected BaseClass(string captionDisplayText)
{
this.CaptionDisplayText = captionDisplayText;
this._firstName = this.GetFirstName();
}
protected string CaptionDisplayText { get; private set; }
protected abstract string GetFirstName();
}
public class DerivedClass : BaseClass
{
protected DerivedClass():base(String.Empty)
{
}
protected override string GetFirstName()
{
return String.Empty;
}
}
Approach 1, CaptionDisplayText, introduces a property and sets it in the constructor whereas approach 2 introduces an abstract method which is overridden in the Derived class.
I know Approach2 is bad if the method was virtual rather than abstract but here it’s abstract which means it is executed before the constructor of the base class and that will be fine.
I’m having 10-15 properties/fields which have to be set by my derived classes so I’m thinking which approach would be more maintainable, readable and testable.
I think approach 1 is more testable whereas approach 2 is much more readable. Approach 2 would also be testable as the mock object will have to implement the abstract members anyway.
Which way is best in your view and is there a third way?
Many thanks,
Doing logic in the constructor is not the way to go if you do want to make the class testable. So by doing this._firstName = this.GetFirstName(); will introduce extra test effort, the code is called even if you do not want to do anything with the first name. In the first approach you could have filled it with a null, which indicates it is not important for your test.