I have a class that I wrote fairly early on in my vb.net programming experience which inherited from another class it really should have composed. The base class is a relatively generic nested dictionary-based collection; let's call the descendant c开发者_如何学Pythonlass a "Car".
Right now there's a lot of code that does things like 'MyCar!Color.st = "Red"' (I use the generic collection rather than real properties to facilitate data interchange with code written in VB6, and also to facilitate comparisons of cars; given three cars X, Y, Z, I can e.g. detect any changes between X and Y and apply those changes to Z).
Is there any nice way to refactor the code to use composition rather than inheritance? Which properties/methods should the "Car" object wrap, and which ones should be accessed through a data-object property? Should a widening conversion be defined between a car and the collection object? Are there any gotchas when doing such refactoring?
You could start by saying Car has a function (or method; not sure of the vb.net terminology) to get its collection - and that function would initially return this
(or self
, or whatever vb calls it).
Now replace all direct references to Car-as-Collection with Car.getCollection()
, both within the Car class and outside.
Finally, make the change: create a member variable, initialize it, return it from getCollection()
, and stop inheriting from Collection. If you missed any references in step 2, they'll show up as compile errors at this point. Fix them and your refactoring is complete.
精彩评论