具有完全不相关的静态方法的静态类有什么问题吗?
我目前正在处理许多 C# 代码隐藏,这些代码最初不是由我编写的。它们被写成一大堆看起来很可怕的代码,现在我的工作就是把它们整理出来。
无论如何,在许多不同的 aspx.cs 文件中存在大量重复的代码。例如,大约有五个代码隐藏文件,它们具有重复多次的完全相同的代码段,以将一些文本输出到文件中。我可以使用以下方法:
private void outputToFile(string text)
在五个不同的代码隐藏文件中重复。
但是,我想知道声明一个名为“MethodHub”的静态类是否是不好的做法,或者只是错误的,它保存了outputToFile(字符串文本)以及十几个彼此不相关的其他方法?
总体目标是从静态类访问这些方法,这样我就可以有效地删除其他类中的数百行代码。
任何人都可以看到这有什么问题,或者我可能遇到任何问题吗?
I am currently working with a lot of C# code-behinds which were not originally written by me. They were written as massive lumps of horrible looking code and it is now my job to sort it out.
Anyway, there are a lot of repetitions of code, in lots of different aspx.cs files. For example, there are about five code-behind files which have exactly the same piece of code repeated a lot to output some text to a file. I could have the method:
private void outputToFile(string text)
repeated in the five different code behind files.
However, I am wondering if it is bad practice or just wrong to declare a static class called something like, "MethodHub" which holds outputToFile(string text) as well as a dozen or so other methods which do not relate to each other?
The overall goal is to access these methods from a static class so I can remove effectively hundreds of lines of code in others.
Can anybody see anything wrong with this, or any problems I may run into?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议通过引入接口
并使用您的实现实现类(例如
代表此接口)来抽象这样的实用程序行为,要点是避免静态类,因为
编辑:
I would suggest to abstract such an utility behaviour by introducing interface
and using your implementation implement class like
on behalf of this interface, the main point is to avoid static class because
EDIT:
当然,持有多个不相关方法的静态类并不是特别优雅,但它比“大量看起来可怕的代码到处重复”模式要好。
当你进行重构时,一定要小步进行。一旦你消除了重复,进一步提高就会变得更容易。
Surely a static class holding several unrelated methods is not particularly elegant, but it's better than the "massive lumps of horrible looking code repeated everywhere" pattern.
When you do refactoring, always do it in small steps. Once you have removed the repetitions, it will be easier to improve further.
当然,您可以使用静态类,但如果该方法使用任何共享字段,则可以避免线程安全问题。
Of course you can use static class, but avoid the thread-safety problem if there is any shared fields used by that method.