Re: Design Question
Rhino wrote:
I have a class named StringUtils containing several utility methods. The
class is stored in a package called "common" because it could potentially
be utilitized by lots of other classes. The methods in this class include
count(), which determines the number of occurrences of a character in a
string, and blanks(), which creates a String containing the number of
blanks specified in the input parameters (for example, blanks(4)
generates a String containing 4 blanks).
I'm trying to figure out if this utility class should be defined final
and have all of its methods defined as static, just the way things work
No. Not declared as final, but with a private constructor.
with the Math class, so that my classes could be referenced statically.
For example, if the methods were static, I would write my code like this:
int num = StringUtils.count("a", "foo");
System.out.println(StringUtils.blanks(4) + "Hello world");
Or would it be better to have a StringUtils NOT be final and NOT make its
methods static? In that case, I'd have to instantiate StringUtils, then
No. Not final, and yes static.
use the reference to the instance to use the methods, like this:
StringUtils myUtils = new StringUtils();
int num = myUtils.count("a", "foo");
System.out.println(myUtils.blanks(4) + "Hello world");
Either way will work but which is the better design and why?
Neither way. Have the class be non-final with a private constructor
and all static methods.
A class who will never have instances with their own state, whose sole
purpose is to provide utility methods for other classes, whose entire
operation depends only on data in the argument lists of those methods,
and ultimately, for whom it really never adds value to have an
instance, is called a "utility class" and likely should have
instantiation prevented and all its members static.
Declaring a class final does not prevent its instantiation. Declaring
its constructor private does, and also prevents subclassing, making
the 'final' declaration redundant, so don't bother with it.
--
Lew