实用类是邪恶的? [英] Utility classes are evil?

查看:180
本文介绍了实用类是邪恶的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到这个线程

如果实用程序课堂是邪恶的,我在哪里放我的通用代码?

并且认为为什么实用程序类是邪恶的?

and thought why are utility classes evil?

编辑 - 这是一个具体的例子,可能是有启发性的。让我说我有一个领域模型,几十个类深。我需要能够使用xml-ify实例。我在父项上做一个toXml方法吗?我做一个MyDomainXmlUtility.toXml帮助器类?这是业务需求跨越整个域模型的情况 - 它是否真的属于实例方法?如果应用程序的xml功能有一堆辅助方法呢?

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.

但是,有时你可以使用实用程序类来分配一些方法在一起 - 一个例子是 java.util.Collections 类,它提供了可以在任何Java集合中使用的一些实用程序。这些不是一个特定类型的集合,而是实现可以在任何集合上使用的算法。

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.

这篇关于实用类是邪恶的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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