问题描述
我看到了这个帖子
如果一个 ""实用程序"类是邪恶的,我将我的通用代码放在哪里?
并想为什么实用程序类是邪恶的?
edit -- 这是一个可能具有指导意义的具体示例.假设我有一个深度为几十个类的域模型.我需要能够 xml-ify 实例.我是否在父级上创建一个 toXml 方法?我要创建一个 MyDomainXmlUtility.toXml 辅助类吗?这是业务需求跨越整个领域模型的情况——它真的属于实例方法吗?如果应用的xml功能上有一堆辅助方法呢?
推荐答案
实用程序类并不完全是邪恶的,但它们可能违反构成良好面向对象设计的原则.在一个好的面向对象设计中,大多数类应该代表一个单一的事物以及它的所有属性和操作.如果你在操作一个事物,那个方法应该是那个事物的成员.
但是,有时您可以使用实用程序类将许多方法组合在一起 - 例如 java.util.Collections 类,它提供了可用于任何 Java 集合的许多实用程序.这些并不特定于一种特定类型的 Collection,而是实现可用于任何 Collection 的算法.
确实,您需要做的是考虑您的设计并确定最适合放置方法的位置.通常,它是作为类内部的操作.但是,有时,它确实是一个实用程序类.但是,当您使用实用程序类时,不要只是将随机方法放入其中 - 按用途和功能组织方法.
问题描述
I saw this thread
If a "Utilities" class is evil, where do I put my generic code?
and thought why are utility classes evil?
edit -- here is a specific example that might be instructive. Lets say I have a domain model that is dozens of classes deep. I need to be able to xml-ify instances. Do I make a toXml method on the parent? Do I make a MyDomainXmlUtility.toXml helper class? This is a case where the business need spans the entire domain model -- does it really belong as an instance method? What about if there are a bunch of auxiliary methods on the xml functionality of the application?
推荐答案
Utility classes aren't exactly evil, but they can violate the principles that compose a good object-oriented design. In a good object-oriented design, most classes should represent a single thing and all of it's attributes and operations. If you are operating on a thing, that method should probably be a member of that thing.
However, there are times when you can use utility classes to group a number of methods together - an example being the java.util.Collections class which provides a number of utilities that can be used on any Java Collection. These aren't specific to one particular type of Collection, but instead implement algorithms that can be used on any Collection.
Really, what you need to do is think about your design and determine where it makes the most sense to put the methods. Usually, it's as operations inside of a class. However, sometimes, it is indeed as a utility class. When you do use a utility class, however, don't just throw random methods into it - organize the methods by purpose and functionality.