This post originated from an RSS feed registered with Agile Buzz
by Keith Ray.
Original Post: Utility Functions as a Code Smell
Feed Title: MemoRanda
Feed URL: http://homepage.mac.com/1/homepage404ErrorPage.html
Feed Description: Keith Ray's notes to be remembered on agile software development, project management, oo programming, and other topics.
Bunches of utility functions, whether bunched together in a "utility class" or not, are often a sign that code isn't object-oriented enough. For example, in Apple's Cocoa implementation, there are a bunch of utility methods for filename-manipulation, in class NSString:
These path-component methods are actually added to the class NSString via a class category, but are viewed as members of the NSString in the documentation and usage.
My point here, with this example, is to raise the question: what are these "path" and "path component" methods doing in class NSString? Perhaps they should be members of a PathName or PathComponent class. (And by the way, pathnames in MacOS X not just unicode, they are "decomposed" unicode, so don't forget to call decomposedStringWithCanonicalMapping; a PathName class would take care that of that for you.)
Like pathnames, URLs are strings with rules for how they are formatted, encoded, etc., so you might expect that Cocoa deals with them using a bunch of utility methods in NSString. But, being a later addition to Cocoa, they are actually their own class: NSURL. This class encodes the requirements of RFCs 1808, 1738, and 2732. It provides methods to access host, get the base URL, test if the URL refers to a file, get absolute and relative forms of an URL, and so on. Apple is moving to using NSURLs instead of pathnames in various Cocoa APIs, and beginning to deprecate the pathname-based APIs, since NSURLs can refer to local files as well as remote web-based resources.
If you've got a bunch of utility methods, look at their names and behaviors to see if they really belong to one or more new classes. If they conceptually belong to an existing class that you can't edit, Objective-C gives you the option to extend that class via a class category.
In other languages, you might have to make a subclass, or in the worst case, leave them as utility methods, but put them together in a class that reflects where you would rather put them. For example, if you write a bunch of string utilities in Java, you can't extend the java.lang.String class, so put them as static methods into your own com.yourcompany.StringExtras class. But first, consider if they are actually representing a concept that deserves to be its own class, like Apple did with URLs.