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:
- Change each
UserControl
to inherit from a new abstract class,AwesomeUserControl
- Move all of the codebehind from each
UserControl
intoAwesomeUserControl
(AwesomeUserControl
does not have an ascx file). - Add abstract getters to
AwesomeUserControl
for any controls from the ascx file of the original UserControls. - 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: