避免在以下遗留代码中进行大量代码更改的优雅方法
在某些遗留代码中,以下代码片段出现数百次:
myObj.ReportGenerator.Preview = reportingObj.PreviewDocument;
...而“ReportGenerator”和“ReportingObj”都是第三方库的实例,因此不可修改。
这段代码在 Windows XP 下运行良好,但在 Windows 7 中运行该程序确实需要以下额外的代码行:
reportingObj.Render();
myObj.ReportGenerator.Preview = reportingObj.PreviewDocument;
不幸的是,这段代码在所有代码库中出现了数百次,手动搜索它们听起来就像一个非常容易出错的过程。
由于“ReportGenerator”和“reportingObj”是第三方,我无法更改它们的 getter / setter。
解决此类问题的优雅方法是什么?
In some legacy code, there are hundreds of occurrences of the following code snippets:
myObj.ReportGenerator.Preview = reportingObj.PreviewDocument;
... whereas both the "ReportGenerator" and the "ReportingObj" are instances of a third party library and therefore not modifyable.
This code did work well under Windows XP, but running the program in Windows 7 does require the following additional line of code:
reportingObj.Render();
myObj.ReportGenerator.Preview = reportingObj.PreviewDocument;
Unfortunately, there are hundreds of occurences of this piece of code all of the code base, and manually searching for them sounds like quite error-prone a process.
As "ReportGenerator" and "reportingObj" are third party, I cannot change their getter / setter.
What are elegant ways of approaching such an issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将
ReportingObj
包装在您自己的类中,在该类中您只需委托给原始 ReportingObj,但对于PreviewDocument
属性检查是否Render()< /code> 被调用,如果没有调用它 - 像这样:
You could wrap
ReportingObj
in a class of your own in which you just delegate to the original ReportingObj, but for thePreviewDocument
property check to see ifRender()
was called and if not call it - something like this:您可以更改
myObj
的类(我认为该类在您的控制之下),并让ReportGenerator
属性返回一个包装类,该包装类可以调用的原始设置器预览
或在调用Render()
后调用它:You could change the class of
myObj
, which I assume is under your control, and have theReportGenerator
property return a wrapper class that either calls the original setter of thePreview
or calls it after callingRender()
:您可能会发现最少的返工量是创建一个静态类,如下所示:
其中 PreviewDocumentType 是从 PreviewDocument 返回的类型,ReportingObject 是报告对象的类型。
然后您可以替换
为
You might find that the least amount of rework will be to create a static class, something like:
where PreviewDocumentType is the type returned from PreviewDocument and ReportingObject is the type of reporting object.
You can then replace
with