Virtual method in constructor and what to do instead

You cannot use a virtual method in the constuctor as the base class constructor will be created first and thus the virtual method on a class that does not exist will be called resulting in an exception under object creation.

The reasons for wanting to call a virtual method in the constructor can be many. I will not discuss the reason but what can be done instead.

1. Live with bloated constructor and thus remove the virtual method and require developers to configure in the class in the constructor.

Benefit:

  • no change in programming

Problem:

  • possible code replication
  • lower maintainability

2. Redo the architecture of the class and the constructor

Benefit:

  • better architecture as a bloated constructor normally is a sign of a bloated responsibility of a class

Problem:

  • might take a long time to change

3. Call an initializer before any properties and methods are used:

Benefit:

  • if the call is not used the initialization the class does not take time (minor benefit)

Problem:

  • the developer needs to remember call the initializer method before use (major problem)
  • the class momentarily slows down when executing the first time (minor problem)

Leave a Reply

Your email address will not be published. Required fields are marked *