扩展.Net类与帮助程序类的最佳实践是哪一种? [英] Which is the best practice to extend a .Net class with a helper class?

查看:97
本文介绍了扩展.Net类与帮助程序类的最佳实践是哪一种?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读有关如何最好地实现帮助程序类的文章,我发现许多人都同意应避免使用帮助程序类".

助手类是一个非常糟糕的主意,应该在大多数时候避免使用"

帖子1-帮助器类是否邪恶?
帖子2-杀死Helper类,第二部分
帖子3-如何重构助手类

他们说的似乎似乎很有意义,但是我应该如何扩展.Net类的功能?哪个是最佳做法?

例如:我需要通过添加一个函数来扩展SerialPort类的功能,以使用通用的Helper类来知道端口是否存在,我可以这样做:

I''ve been reading some post on how best to implement a helper class and I found that many people agree that the "helper classes" should be avoided.

"helper classes are an extraordinarily bad idea that should be avoided most of the time"

Post 1 - Are Helper Classes Evil?
Post 2 - Killing the Helper class, part two
Post 3 - How to Refactor the Helper Class

It seems that what they say makes sense, but how should I extend the functionality of a .Net class? which is the best practice to do this?.

For instance: I need to extend the functionality of the SerialPort class by adding a function to know if a port exists, with a common Helper Class I could do this:

Public NotInheritable Class Helper

   Public Shared Function SerialPortExists(ByVal portNumber as Integer) As Boolean
      Dim ports As String()
      ports = SerialPort.GetPortNames()
      Return Array.Exists(Of String)(ports, Function(p) p.Equals("COM" & portNumber.ToString()))
   End Function

End Class





how can I accomplish this using best practices?

推荐答案

好吧,实际上并没有硬性规定.

我个人的看法是,如果这是您唯一可以帮助SerialPort的方法,或者您有一些与之相关的方法是创建一个SerialPortHelper类,然后将该方法放到那里.此类中应仅包含与SerialPort相关的方法,除此之外没有.

我只读了您链接的第一篇文章,但它通常指的是为其他方法创建的通用捕获所有"类,这些方法不适用于其他任何地方.这是不好的做法,我倾向于同意.

我也不觉得只需要向它添加单个方法就可以从SerialPort类继承.如果您还不止这些,请放心.
Well, there really isn''t a hard and fast rule for this.

My personal opinion is if this is the only method you have that helps SerialPort or you have a few methods related to it is to create a SerialPortHelper class and drop the method in there. This class should noly have methods in it related to SerialPort, NOTHING ELSE.

I only read the first post you linked but what it was generally referring to was creating a general purpose "catch all" class for miscellaneous methods that don''t fit anywhere else. This is bad practice and I tend to agree.

I also don''t feel the need to Inherit from the SerialPort class just to add a single method to it. If you''ve got more than that, feel free.


这篇关于扩展.Net类与帮助程序类的最佳实践是哪一种?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆