Good design practice has only a constructor without parameters without a base class?

In base class constructors, I always see a constructor without parameters: for example,

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

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

  public abstract BaseClass {... protected BaseClass(string initObj) { } ...} 
+4
source share
6 answers

Yes, for a base class, the requirement of a parameterized constructor is acceptable. It just imposes a requirement that any classes that inherit must provide a value to the base constructor.

+12
source

In most cases, derived classes have some form of parameterized constructors. Therefore, when these constructors are called, they can still invoke the constructor without parameters:

 public employee(int age) : base(this) 

Answer: if you just need to add it, there is nothing wrong with that. Think of the base class of a business object that requires some statements to provide a phone number or email address. You want derived classes to load these business rules into them. If you did not have a base class constructor, you could not add these rules to objects of the derived class.

+2
source

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

+2
source

What the author of the base class does in your first example, just make sure that public constructors are not displayed. Probably, the base class does not require anything special in the constructor, but if you do not write it, the compiler will add a default constructor to you (less parameter).

I do not think this is particularly useful. You still can't create abstract classes.

+2
source

It is acceptable. Whether it is necessary or useful depends entirely on the (design) classes.

+1
source

Yes, this is a perfectly acceptable design solution, only it should make sense for the base class - presumably in order to initialize its own elements from the parameter. In addition, this imposes a restriction on derived classes: either they must take place literally, or impose similar restrictions on their clients or on additional derived classes.

+1
source

Source: https://habr.com/ru/post/1304776/


All Articles