lundi 8 mai 2017

Code refactoring: two but not all the derived classes of a base class have an identical override method

In C#, a class B serves as the only base class of three classes C, D and E.

B has a virtual method, which is overridden in C, D and E. C and D have the same implementation of the override method, different from the one in E.

C and D don't have other things in common.

How can I remove code duplicate between C and D?

Two ways that I am considering are:

  1. create a new class F derived from B and make C and D derived from F instead of B. Move the common override method in C and D to F. I think it is overkill, since C and D don't have other things in common.

  2. create a new method in B, named differently from the virtual method, and implemented identically to the common override methods in C and D. Then change the implementations of the common override methods in C and D, to just a call the new method in B. Is this an elegant solution? Is it some design pattern or Object-Oriented trick?

Thanks.

I don't add C# as a tag, because I think the question is not C# specific, but general to all object oriented languages.

Aucun commentaire:

Enregistrer un commentaire