I wish I had my copy handy, but I would say thet "Extract Composite" is a special case of "Extract Superclass" A composite is a specific type of inheritance relationship, and I guess the author felt it needed to be called out separately. The diagram does indeed illustrate the kind of operations often done with composites. I think in the example given, not all subclasses are composites though, so that functionality cannot be pulled into the base class. Still, it does feel a bit like the author was just padding the book a bit :)
Why and When should I "Extract Composite" instead of "Extract Superclass"
-
13-10-2022 - |
Question
I'm reading a book called Refactoring to Patterns, and in this book there is a section titled: Extract Composite (page 214).
What it suggests is that if a bunch of subclasses have common functionality you should extract that functionality to a new superclass. This sounds pretty straight forward.
What is the difference between Extract Composite
and Extract Superclass
?
Well, according to the reading and the diagrams... the composite should be a new superclass to your child classes. See the following diagram:
Question: What is the purpose of creating a new "CompositeTag" superclass? Why wouldn't you want to just move the code-duplication to its original base class (Node)?
La solution
Autres conseils
Here's an analogy in terms of Visual
and UIElement
from WPF. Let's pretend we're developing some controls, and we discover that (for whatever strange reason) we don't have mouse events, and that buttons kind of need them.
We could put mouse events in Visual
, or we could put them in UIElement
. Since it doesn't make sense to have mouse events on something that's not part of a GUI, it logically belongs in UIElement
, and that's where we put them.
Answer: Semantics, and especially the Single Responsibility Principle. Visual
should take care of things like effects and transforms, while UIElement
should take care of focus and input etc.
I'd try to offer a more pertinent example, but I don't have a concrete set of classes to work with. If you can logically separate functionality into self-contained sub-classes, by all means do so.