On Fri, 25 Jul 2008 16:09:41 -0700, K Viltersten <tm**@viltersten.com>
wrote:
Suppose there is the following class structure.
class S {...}
class A : S {...}
class B : S {...}
class A1 : A {void m(){...}}
class B1 : B {void m(){...}}
class B2 : B {...}
Just to clarify the issue. A1 and B1 share a
method (void m() ) AND B2 doesn't have that
method. Hence, it shouldn't be placed in any
of the extended classes S, A nor B.
Still, i feel that i'd like to put the method
in a common repository/class/whatever, to
avoid repetition and make the changes to it
simpler (only one copy needs to be edited).
It also makes the code less prone to errors.
Can it be done in C#? What would be a smart
solution for it?
My first thought is that if classes A1 and B1 have the method but don't
share a base class, while classes B1 and B2 share their immediate base
class but don't share the method, that there may be something broken with
your inheritance hierarchy.
But let's take as granted that the hierarchy is sound. Then the question
is how to share the implementation. But that's hard to answer without
knowing what the method actually does. What is it about the method that
causes it to be in both A1 and B1? Is it related to the base class S that
they share? If so, what is it about class B2 that causes it to not have
the same method?
If the method is unrelated to the base class S, then the question is
what's similar about A1 and B1 that causes them to have the same method?
Does the method need access to private/protected members in classes A1 and
B1? If not, do you think maybe it would make sense to create extension
methods for the classes, where the extension methods both call a shared
implementation?
These are just a few of the questions that come to mind. My implication
being that we really don't have enough information to answer the
question. At the very simplest, the obvious answer to your question is to
have a utility class with the implementation of your method in it, and
which is called by the method in each class. The extension method
suggestion is just a short hop from there, being basically the same
approach but with some cleaner syntax.
But without knowing more about the design, I don't see a way to provide a
really insightful answer.
Pete