使用 Vbex2005 将继承重构为组合
我在 vb.net 编程经验中很早就编写了一个类,它继承自它真正应该组成的另一个类。基类是一个相对通用的基于嵌套字典的集合;我们将后代类称为“Car”。
现在有很多代码可以执行诸如 'MyCar!Color.st = "Red"' 之类的操作(我使用通用集合而不是实际属性来方便与 VB6 编写的代码进行数据交换,也方便对汽车进行比较;给定三辆车 X、Y、Z,我可以检测 X 和 Y 之间的任何变化并将这些变化应用到 Z)。
有没有什么好的方法来重构代码以使用组合而不是继承? “Car”对象应该包装哪些属性/方法,以及应该通过数据对象属性访问哪些属性/方法?是否应该在汽车和集合对象之间定义扩大转换?进行此类重构时是否存在任何问题?
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 class 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以首先说 Car 有一个函数(或方法;不确定 vb.net 术语)来获取其集合 - 该函数最初会返回
this
(或self,或者任何 vb 的称呼)。
现在,将 Car 类内部和外部对 Car-as-Collection 的所有直接引用替换为
Car.getCollection()
。最后,进行更改:创建一个成员变量,对其进行初始化,从
getCollection()
返回它,并停止从 Collection 继承。如果您在第 2 步中错过了任何引用,此时它们将显示为编译错误。修复它们,您的重构就完成了。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
(orself
, 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.