开发者

is it good design practice to only have a parameterless base class constructor?

In base class constructors I always see a parameterless constructor, like so:

   public abstract B开发者_运维技巧aseClass {...
protected BaseClass() { }
...}

but is it acceptable design to include a parameter in the base class constructor?

   public abstract BaseClass {...
protected BaseClass(string initObj) { }
...}


Yes, it is acceptable for a base class to require a parameterized constructor. This simply imposes a requirement that any classes which inherit must provide a value to the base constructor.


In most cases the derived classes have some form of parameterized constructors. So when those constructors are called they can still call the parameterless base constructor:

public employee(int age) : base(this)

The answer is if you need one just add one, there is nothing wrong with that. Think of a business object base class that requires some validations to say a phone number or email address. You want to ensure the derived classes get these business rules loaded into them. If you did not have the base class constructor you could not add these rules to your derived class objects.


It is a good practice if the object cannot be used or has dependencies on every method on this class. For instance, if you have a class that have the same parameters in all the functions, it would be better to set that in the constructor, so the function signature is smaller.


What the writer of the base class is doing in your first example is just making sure that no public constructors are exposed. Probably the base class needs nothing special in the constructor but, if you don't write any, the compiler will add the default (parameter-less) constructor for you.

Not that I think this is specially useful. You cannot instantiate an abstract class anyway.


It is certaibly acceptable. Whether is is needed or useful depends entirely on the (design of) the classes.


Yes, its a perfectly acceptable design decision, only it must make sense for the base class - presumably to initialise its own members from the parameter. Also, it imposes a restriction on derived classes: either they must pass in a literal, or impose a similar restriction on their clients or further derived classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜