gpt4 book ai didi

oop - 开设 Misc Utilities 类(class)是不是很糟糕?

转载 作者:行者123 更新时间:2023-12-03 23:21:14 25 4
gpt4 key购买 nike

关闭。这个问题是opinion-based .它目前不接受答案。












想改进这个问题?更新问题,以便 editing this post 提供事实和引用来回答它.

3年前关闭。




Improve this question




我们公司保留了一个 MiscUtilities 类,该类仅由公共(public)静态方法组成,这些方法通常执行不相关的任务,例如将日期从 String 转换为 Calendar 并将 ArrayLists 写入文件。我们在其他类中引用它,发现它非常方便。但是,我看到过那种在 TheDailyWTF 上被 mock 的 Utilities 类。我只是想知道这类类(class)是否有任何实际的缺点,以及替代方案是什么。

最佳答案

我不会给出个人意见,而是引用 Java 社区的权威来源,以及来自 2 个非常有名的第三方库的示例。

Effective Java 2nd Edition, Item 4: Enforce noninstantiability with a private constructor 的引用:

Occasionally you'll want to write a class that is just a grouping of static methods and static fields. Such classes have acquired a bad reputation because some people abuse them to avoid thinking in terms of objects, but they do have valid uses. They can be used to group related methods on primitive values or arrays, in the manner of java.lang.Math or java.util.Arrays. They can also be used to group static methods, including factory methods, for objects that implements a particular interface, in the manner of java.util.Collections. Lastly, they can be used to group methods on a final class, instead of extending the class.



Java 库有许多此类实用程序类的示例。
  • Apache Commons Lang关注 Type Utils命名约定
  • ArrayUtils , StringUtils , ObjectUtils , BooleanUtils
  • Guava关注 Type s命名约定
  • Objects , Strings , Throwables , Collections2 , Iterators , Iterables , Lists , Maps
  • package summary实际上有一个关于 static 类的特定部分实用方法
  • 另一个entire package只包含用于处理 Java 原语的实用程序类, Ints , Floats , Booleans


  • 简短的摘要
  • 更喜欢良好的 OOP 设计,总是
  • static实用程序类可以有效地将相关方法分组在:
  • 基元(因为它们不是对象)
  • 接口(interface)(因为它们自己没有任何具体的东西)
  • final类(因为它们不可扩展)
  • 总是喜欢良好的组织
  • SomeType 的组实用程序方法至SomeType UtilsSomeType s
  • 避免使用包含不同类型/概念的各种不相关任务的单个大型实用程序类
  • 关于oop - 开设 Misc Utilities 类(class)是不是很糟糕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3531580/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com