Is it appropriate to use inheritance to prevent code duplication of the logic for a user control

asp.netinheritance

Suppose I have two or more UserControl implementations with vastly different implementations but near identical code-behind. One strategy to avoid code duplication is as follows:

  1. Change each UserControl to inherit from a new abstract class, AwesomeUserControl
  2. Move all of the codebehind from each UserControl into AwesomeUserControl (AwesomeUserControl does not have an ascx file).
  3. Add abstract getters to AwesomeUserControl for any controls from the ascx file of the original UserControls.
  4. Implement these getters in each UserControl.

This strategy works extremely well and is easy to maintain. However, it also introduces stupid scaffolding code; every new implementation of AwesomeUserControl has a bunch of getters to hook AwesomeUserControl the UI elements inside of the new control. Any time I find myself using a strategy which requires copy-pasted scaffolding code, I worry that I am doing something wrong. Though it does have a nice effect of failing to compile if the UI elements are missing (as opposed to skipping the scaffolding code in favor of reflection and required naming).

Is this use of inheritance reasonable?

Best Answer

Vastly different implementations? Sounds like a bad candidate for a common abstract parent class, don't you think?

Otherwise, you have to be more precise than AwesomeUserControl. What are the exact controls which share the same logic? What logic is shared?

As an illustration, here's a copy-paste from an answer I wrote a few days ago:

  • Either two classes are related (for example both Cat and Dog can be fed, and it takes the same steps to feed them both, except the food which will change), in which case, create an inheritance (in my example, a parent class Pet),

  • Or two classes are unrelated, and just rely on the same method. For example, WebRequest class may rely on GetSlug¹ to find the slug of the current request; Customer may also rely on GetSlug to normalize the name of the customer for further search purposes. However, WebRequest and Customer are totally unrelated, and it makes no sense to create a common object for those classes.

    Here, the solution would be to call a common method from those two classes, by instantiating the third class containing this method. For example, both RequestUri and CustomerName may become objects implementing ISlug interface.

Related Topic