Our company keeps a MiscUtilities class that consists solely of public static methods that do often unrelated tasks like converting dates from String to Calendar and writing ArrayLists to files. We refer to it in other classes and find it pretty convenient. However, I've seen that sort of Utilities class derided on TheDailyWTF. I'm just wondering if there's any actual downside to this sort of class, and what the alternatives are.
Rather than giving personal opinion, I will quote from an authoritative source in the Java community, and examples from 2 very reputable third party libraries.
A quote from 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 andstatic
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 ofjava.lang.Math
orjava.util.Arrays
. They can also be used to groupstatic
methods, including factory methods, for objects that implements a particular interface, in the manner ofjava.util.Collections
. Lastly, they can be used to group methods on afinal
class, instead of extending the class.
Java libraries has many examples of such utility classes.
Type
Utils
naming convention
ArrayUtils
, StringUtils
, ObjectUtils
, BooleanUtils
, etcType
s
naming convention
Objects
, Strings
, Throwables
, Collections2
, Iterators
, Iterables
, Lists
, Maps
, etc.static
utility methodsInts
, Floats
, Booleans
, etc.static
utility classes have valid uses to group related methods on:
final
classes (since they're not extensible)SomeType
to SomeType
Utils
or SomeType
s
Convenient, most likely.
Possible to grow into a scary, hard to maintain swiss-army-rocket-chainsaw-and-floor-polisher, also most likely.
I'd recommend separating the various tasks into separate classes, with some logical grouping besides "won't fit anywhere else".
The risk here is that the class becomes a tangled mess nobody fully comprehends and noone dares to touch - or replace. If you feel that is an acceptable risk and/or avoidable under your circumstances, nothing really prevents you from using it.
I've never been a fan of the MiscUtilities class. My biggest issue is that I never know what is in it. Anything filed under miscellaneous is not discoverable. Instead I prefer to use a common dll that I can import into my projects that contains well named, separated classes for different purposes. The difference is subtle, but I find that it makes my life a little easier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With