您对如何组织和命名实用程序类有任何意见吗?
每当我遇到一些代码重复时,可能只是几行代码,我将它们移动到一个实用程序类。
过了一段时间,我倾向于得到很多小的静态类,通常只有一个方法,我通常把它放在 utility
中。因类而臃肿的命名空间。
例子:
ParseCommaSeparatedIntegersFromString( string )
CreateCommaSeparatedStringFromIntegers( int[] )
CleanHtmlTags( string )
GetListOfIdsFromCollectionOfX( CollectionX )
CompressByteData( byte[] )
通常,命名约定告诉您将您的类命名为名词。我经常上很多课,比如
HtmlHelper
, CompressHelper
但它们的信息量不是很大。我也尝试过像 HtmlTagCleaner
这样非常具体,通常每个实用程序方法都有一个类。您对如何命名和分组这些辅助方法有任何想法吗?
最佳答案
我相信有一个连续的复杂性,因此相应的组织 .示例如下,根据您的项目和实用程序的复杂性进行选择,并适应其他约束:
或者,如果它们适合,这些类可以拆分为几个非帮助程序包。
或者,如果它们适合,可以将包拆分为几个非辅助包。
在每个分组级别(包、类):
对于项目,我通常在 super 包名称中重复常见的含义。虽然理论上不是我的首选,但我没有在我的 IDE (Eclipse) 中看到从哪个项目中导入了一个类,因此我需要重复这些信息。该项目实际上仅用作:
Please note that all the above applies to dynamic methods as well, not only static ones. It's actually our good practices for all our code.
Now that I tried to answer your question (although in a broad way), let me add another thought
(I know you didn't ask for that).
静态方法(使用静态类成员的方法除外)在没有上下文的情况下工作,所有数据都必须作为参数传递。我们都知道,在 OO 代码中,这不是首选方式。理论上,我们应该寻找与该方法最相关的对象,并将该方法移到该对象上。请记住 代码共享不必是静态的 ,它只需要是公开的(或可见的)。
将静态方法移动到何处的示例:
尽管这种方法在 OO 纯粹主义者看来似乎是移动的,但我们发现从长远来看这实际上对我们有帮助(当我们想要对其进行子类化以改变算法时,它被证明是无价的)。 Eclipse 在不到一分钟的时间内移动了一个方法(所有验证),当我们寻找一些代码时,或者当我们不再对已经编码的方法进行编码时,我们获得的 yield 远远超过一分钟。
Limitations : some classes can't be extended, usually because they are out of control (JDK, libraries ...). I believe this is the real helper justification, when you need to put a method on a class that you can't change.
Our good practice then is to name the helper with the name of the class to extend, with Helper suffix. (StringHelper, DateHelper). This close matching between the class where we would like the code to be and the Helper helps us find those method in a few seconds, even without knowledge if someone else in our project wrote that method or not.
关于naming-conventions - 实用程序类和方法的命名约定和结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1271254/