Design Question

R

Rhino

This question is completely unrelated to the one I just asked about
initializing a Map....

--

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
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
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?

And no, this is not a homework question. It's just one of many gaps in my
own understanding ;-)
 
L

Lew

Rhino said:
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.
 
E

Eric Sosman

This question is completely unrelated to the one I just asked about
initializing a Map....

--

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
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
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?

The methods as you describe them sound like they ought to
be static. There's no state associated with a StringUtils
instance that wouldn't also be associated with every other
StringUtils instance, so one asks: What value does an instance
bring to the party? That is, in

StringUtils ut1 = new StringUtils();
int num1 = ut1.count("a", "foo");

StringUtils ut2 = new StringUtils();
int num2 = ut2.count("a", "foo");

.... why bother with ut2 when ut1 would do exactly the same
thing, exactly as well?

Even if blanks() maintains a cache of already-generated
Strings that it can recycle to satisfy future requests, I'd
say the cache belongs to the class and not to an instance.
If ut1.blanks(4) caches a String, shouldn't ut2.blanks(4)
be able to re-use that same String instead of caching its own?

The question of whether to make StringUtils final is another
matter, and seems independent of whether these methods are static.
 
M

markspace

Rhino said:
I have a class named StringUtils containing several utility methods.


I asked a question like this here long ago. What I think now is that
you almost certainly should make the class final, and all the methods
static.

If you do need to keep state, make a new class, don't reuse the
StringUtils, except as a factory.

And as Lew says, the best way to make such a class final is to make the
constructor private. That kills two birds with one stone. First the
class is final because subclasses can't call the constructor, and second
other classes can make instances of your utility class either.

One last idea, I have a string utility class that is declared something
like this:

package mypackage.common.stringutils;

public class StringUtils { ...

In other words, the package name is stringutils, and so is the class
name. This allows me to easily add classes to the stringutils package,
without trying to overload StringUtils to hold state. For example, if
RepeatedString is a class that tries to be faster than blanks(), but
requires a max length:

package mypackage.common.stringutils;

public class RepeatedString {
final private String repeated;
public RepeatedString( String s, int dups ) {
StringBuilder sb = new StringBuilder( s.length() * dups );
for( int i = 0; i < dups; i++ ) {
sb.append( s );
}
repeated = sb.toString();
}
public String subStr( int count ) {
return repeated.substring( 0, count );
}
}

This just allows me to have a nicer place to put RepeatedString (under
stringutils) rather than have to find a place to shoe-horn it in
somewhere else.
 
L

Lew

I asked a question like this here long ago.  What I think now is that
you almost certainly should make the class final, and all the methods
static.

If you do need to keep state, make a new class, don't reuse the
StringUtils, except as a factory.

And as Lew says, the best way to make such a class final is to make the
constructor private.  That kills two birds with one stone.  First the

When one speaks of making a class "final" in Java, one is referring to
use of the 'final' keyword. Using "final" to mean something different
is confusing here.
 
A

Arne Vajhøj

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
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
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?

Make the methods that are static in nature static. And that
may be all of them.

And no need to mess around with final or private constructor.
It is pointless but harmless if somebody would inherit or
initialize the class.

Make the methods static and move on to a real problem.

Arne
 
L

Lew

Arne said:
And no need to mess around with final or private constructor.
It is pointless but harmless if somebody would inherit or
initialize the class.

Pointless code is harmful by virtue of its pointlessness.

You attached a cost of zero to pointless code, but its cost is larger than
zero. "Pointless" means that it provides no benefit, ergo cost exceeds benefit.

It seems clear that instantiation or (especially) inheritance of a utility
class is pointless, of no benefit. It has a cost in extra code coupling,
reduction in self-documentation, muddier expression of type relationships and
just plain extra stuff to scratch a maintainer's "wtf?" nerve over the life of
the software. The burden is to justify its existence, not the mandate against it.

The existence of code to prevent instantiation and inheritance has a cost. In
context of a conservative coding style that armors against error, the burden
of the cost is shared by the commitment to code safety, but it still is a
small burden to add a private constructor with the aid of a code template.
The benefit is the elimination of the cost of pointless code, and a cleaner
expression of purpose self-documented in the code. Potential abuses of the
type structure will be caught at compile time rather than maintenance time, at
less cost than the latter, and are not deployable.

Synergistically, the habit of such conservatisms creates overall benefit that
is greater than the sum of the incremental benefits, at a cost that is
somewhat less than the simple sum due to learning curve effects and economies
of scale. Small benefits have their place in this scheme. If something is
easy, correct and even a little beneficial on balance, why not include it in
the first place, and in the end reap the greater benefit of a system
comprising well-polished, simplified and correct components?
 
A

Arved Sandstrom

Lew said:
Pointless code is harmful by virtue of its pointlessness.

You attached a cost of zero to pointless code, but its cost is larger
than zero. "Pointless" means that it provides no benefit, ergo cost
exceeds benefit.

It seems clear that instantiation or (especially) inheritance of a
utility class is pointless, of no benefit. It has a cost in extra code
coupling, reduction in self-documentation, muddier expression of type
relationships and just plain extra stuff to scratch a maintainer's
"wtf?" nerve over the life of the software. The burden is to justify
its existence, not the mandate against it.

The existence of code to prevent instantiation and inheritance has a
cost. In context of a conservative coding style that armors against
error, the burden of the cost is shared by the commitment to code
safety, but it still is a small burden to add a private constructor with
the aid of a code template. The benefit is the elimination of the cost
of pointless code, and a cleaner expression of purpose self-documented
in the code. Potential abuses of the type structure will be caught at
compile time rather than maintenance time, at less cost than the
latter, and are not deployable.

Synergistically, the habit of such conservatisms creates overall benefit
that is greater than the sum of the incremental benefits, at a cost that
is somewhat less than the simple sum due to learning curve effects and
economies of scale. Small benefits have their place in this scheme. If
something is easy, correct and even a little beneficial on balance, why
not include it in the first place, and in the end reap the greater
benefit of a system comprising well-polished, simplified and correct
components?
What all this is saying is that Java is not quite pure OOP enough in
some areas, like the fact that it has primitives, but that in others
it's too pure, like not having a straightforward way to write a chunk of
procedural code.

I'm with you on the provision of a private ctor for the reasons that you
state, but because I find the whole shoehorning of procedural code into
a class to be faintly ugly I'm with Arne as well, in thinking that it's
not a topic that deserves a great deal of time.

AHS
 
R

Rhino

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.

I've read all the replies to this thread and have been trying to post
followup questions since yesterday afternoon; unfortunately, I've had
major problems with the news server and have finally had to resort to
posting via Google groups. Sorry for the delay!

--
Am I correct in assuming that a valid example of 'state' is the Locale
used by the class/methods to generate error messages?

My StringUtils class generates a substantial number of error messages
via the standard ResourceBundle mechanism and delivers them in a
Locale-sensitive fashion. I have two constructors for StringUtils, one
that has no parameters and simply uses the default Locale, and the
other, which has the Locale desired by the user as the single
parameter.

Now, if I want to continue to deliver Locale-sensitive messages and if
I make the constructors private, I can't tell the methods which Locale
to use in selecting message files via the constructor. I suppose I
could add a Locale parameter to each method's parameter list but that
seems ugly.

What's the best way to handle Locale-sensitive messages if I want to
keep my methods static and my constructors private?

Or does this factor change everything and now justify keeping the
StringUtils constructors public and its methods non-static?
 
R

Rhino

I asked aquestionlike this here long ago.  What I think now is that
you almost certainly should make the class final, and all the methods
static.

If you do need to keep state, make a new class, don't reuse the
StringUtils, except as a factory.
Sorry, I'm not following this strategy.

I'm not entirely sure what constitutes 'state' in this context but I
suspect that the Locale-specific messages I am generating may qualify.
As I've explained in my reply to Lew's first response, I am generating
Locale-sensitive error messages. I have two constructors. One
constructor has no parameters and uses the default Locale; the other
constructor has the Locale as its parameter and generates messages
appropriate for that Locale. If this counts as "state" for the
purposes of our current discussion, I'm not clear on what you're
proposing. How do I use StringUtils as a factory to feed the new class
that you are suggesting?

And as Lew says, the best way to make such a class final is to make the
constructor private.  That kills two birds with one stone.  First the
class is final because subclasses can't call the constructor, and second
other classes can make instances of your utility class either.

One last idea, I have a string utility class that is declared something
like this:

   package mypackage.common.stringutils;

   public class StringUtils { ...

In other words, the package name is stringutils, and so is the class
name.  This allows me to easily add classes to the stringutils package,
without trying to overload StringUtils to hold state.  For example, if
RepeatedString is a class that tries to be faster than blanks(), but
requires a max length:

   package mypackage.common.stringutils;

   public class RepeatedString {
     final private String repeated;
     public RepeatedString( String s, int dups ) {
       StringBuilder sb = new StringBuilder( s.length() * dups );
       for( int i = 0; i < dups; i++ ) {
         sb.append( s );
       }
       repeated = sb.toString();
    }
    public String subStr( int count ) {
      return repeated.substring( 0, count );
    }

}

This just allows me to have a nicer place to put RepeatedString (under
stringutils) rather than have to find a place to shoe-horn it in
somewhere else.

I'm not quite clear on why this is better than simply creating a
RepeatedString method in the StringUtils claas. Can you clarify,
please?
 
M

markspace

I'm quoting your entire message below since a lot of folks here filter
Google groups.

Short answer: If you're creating a class with instance variables,
that's "state" and you should not be using static methods. Basically,
since you left out this important detail, all the advice you got on this
thread is wrong.

Yes, a class that needs constructors for arguments/initialization needs
public constructors.

public class StringUtils {
private Locale locale;
public StringUtils( Locale l ) {
locale = l;
}
public String count( String dup, int count ) {
...
}
...
}

Note now I'm avoiding the static keyword everywhere.
 
M

markspace

Rhino said:
Sorry, I'm not following this strategy.

I'm not entirely sure what constitutes 'state' in this context but I


It basically means "an instance variable."

suspect that the Locale-specific messages I am generating may qualify.
As I've explained in my reply to Lew's first response, I am generating
Locale-sensitive error messages. I have two constructors. One
constructor has no parameters and uses the default Locale; the other
constructor has the Locale as its parameter and generates messages
appropriate for that Locale. If this counts as "state" for the
purposes of our current discussion, I'm not clear on what you're
proposing. How do I use StringUtils as a factory to feed the new class
that you are suggesting?



I'm not quite clear on why this is better than simply creating a
RepeatedString method in the StringUtils claas. Can you clarify,
please?


RepeatedString has state (the "repeated" field), we all assumed your
static class did not. Mixing the two would be a bad idea.
 
L

Lew

Rhino said:
Am I correct in assuming that a valid example of 'state' is the Locale
used by the class/methods to generate error messages?

If the locale is maintained between calls, then its part of the object
state. If it's only used as a method parameter, then it's not part of
the object state but just the current invocation.
My StringUtils class generates a substantial number of error messages
via the standard ResourceBundle mechanism and delivers them in a
Locale-sensitive fashion. I have two constructors for StringUtils, one
that has no parameters and simply uses the default Locale, and the
other, which has the Locale desired by the user as the single
parameter.

If you have a meaningful constructor, you have left static-land and
are now committed to instance-land. If you are building a utility
class, everything must be static. If you are building a helper class,
then make it instantiable and don't use static methods.
Now, if I want to continue to deliver Locale-sensitive messages and if
I make the constructors private, I can't tell the methods which Locale
to use in selecting message files via the constructor. I suppose I
could add a Locale parameter to each method's parameter list but that
seems ugly.

"Ugly"? "Ugly"? What is that supposed to mean?

If you are making a utility class with all static methods, you need to
pass the Locale as an argument.

If you are making a helper class with instance methods, then by all
means use the constructors to initialize a private final variable for
Locale.
What's the best way to handle Locale-sensitive messages if I want to
keep my methods static and my constructors private?

Pass the Locale as a method argument.

Remember, the utility class with all static methods must have only
class-level state, not instance-level.

"State" is a standard term; it refers to the current values of
variables associated with the instance.

You can have 'static' state, that is, state maintained by class
variables as opposed to instance variables. The state is associated
with the class as such, and thus does not hurt your staticness.

Static state risks thread issues; the safest thing for static state is
that it be immutable where it exists at all.
Or does this factor change everything and now justify keeping the
StringUtils constructors public and its methods non-static?

Since your analysis indicates that you need multiple instances of your
'StringUtil' class, each with different behaviors, you have answered
your own question.
 
L

Lew

Sorry, I'm not following this strategy.

I'm not entirely sure what constitutes 'state' in this context but I

Same thing it means in any other context - "state" is the aggregation
of the observable aspects of the (class or instance) object, i.e., the
values of its attributes, in particular, those that affect its
behavior.

markspace is telling you that if you write a class to be stateless,
then need to add state, it's not a good idea to mingle state with a
stateless class. You're better off separating the behaviors into a
stateless class and a stateful one.
suspect that the Locale-specific messages I am generating may qualify.

Depends on how you do it - if you store the Locale as part of the
state, then yes, it affects things.
As I've explained in my reply to Lew's first response, I am generating
Locale-sensitive error messages. I have two constructors. One

Constructors means no longer being all static.
constructor has no parameters and uses the default Locale; the other
constructor has the Locale as its parameter and generates messages
appropriate for that Locale. If this counts as "state" for the

Is it an observable attribute of the object?

Does its value affect the object's behavior in any way?

Does the value persist between method calls?
purposes of our current discussion, I'm not clear on what you're

State is state, purpose notwithstanding.
proposing. How do I use StringUtils as a factory to feed the new class
that you are suggesting?

You add a factory method to create an instance of the stateful class.
 
L

Lew

It basically means "an instance variable."

Unless you're talking about a static variable. That's state, too.

The former is instance state. The latter is class state, or "static"
state.
 
R

Rhino

I'm quoting your entire message below since a lot of folks here filter
Google groups.

Short answer:  If you're creating a class with instance variables,
that's "state" and you should not be using static methods.  Basically,
since you left out this important detail, all the advice you got on this
thread is wrong.

Yeah, sorry about that omission. I didn't take the Locale issue into
effect when I asked the original question, then my news server issue
prevented me posting until now.
Yes, a class that needs constructors for arguments/initialization needs
public constructors.

   public class StringUtils {
     private Locale locale;
     public StringUtils( Locale l ) {
       locale = l;
     }
     public String count( String dup, int count ) {
       ...
     }
     ...
   }

Note now I'm avoiding the static keyword everywhere.
And that's how the code was when I posted the original question....
 
R

Rhino

If the locale is maintained between calls, then its part of the object
state.  If it's only used as a method parameter, then it's not part of
the object state but just the current invocation.


If you have a meaningful constructor, you have left static-land and
are now committed to instance-land.  If you are building a utility
class, everything must be static.  If you are building a helper class,
then make it instantiable and don't use static methods.


"Ugly"?  "Ugly"?  What is that supposed to mean?
Sorry, that wasn't very precise phrasing.

If I pass Locale in to each method, then I will need to revise each
method to include a Locale parameter; some versions of some methods
already have 7 parameters, which already seems excessive and 8 is that
much worse. Also, since I'd like to give the user the option of using
the default Locale, then I need two versions of each method, one that
does not specify Locale and uses the default Locale and one that lets
the user specify the Locale. That's what I mean by ugly.

Given that classes in the Java API don't typically use that approach,
I'm assuming this is not an approach that I should adopt either....
 
R

Rhino

Same thing it means in any other context - "state" is the aggregation
of the observable aspects of the (class or instance) object, i.e., the
values of its attributes, in particular, those that affect its
behavior.

markspace is telling you that if you write a class to be stateless,
then need to add state, it's not a good idea to mingle state with a
stateless class.  You're better off separating the behaviors into a
stateless class and a stateful one.
I'm not clear on how exactly I would separate my behaviours into a
stateless class and a stateful one. Can you give me (or point me to)
an illustration of this technique? My OO theory is not that strong so
forgive me for asking something that should probably be obvious to me.
Depends on how you do it - if you store the Locale as part of the
state, then yes, it affects things.


Constructors means no longer being all static.


Is it an observable attribute of the object?

Does its value affect the object's behavior in any way?

Does the value persist between method calls?
Given that different invocations of StringUtils might choose to
generate messages in different languages, I assume the answer to your
three questions is yes.
State is state, purpose notwithstanding.


You add a factory method to create an instance of the stateful class.
Again, can you clarify this a bit? You don't necessarily need to write
an example; just pointing to a document or tutorial that contains an
example would be just fine. I'm not sure where to look for such a
thing.

Thank you for your patience!
 
J

Jeff Higgins

My StringUtils class generates a substantial number of error messages
via the standard ResourceBundle mechanism and delivers them in a
Locale-sensitive fashion.

How are you delivering the error messages? If you are using the
Exception mechanism can your StringUtils class method callers do their
own translation and let StringUtils do its own thing?
 
M

markspace

Lew said:
Unless you're talking about a static variable. That's state, too.

The former is instance state. The latter is class state, or "static"
state.


Yes, but often creating a singleton object like this is pretty bad.
(Note that the normal singleton pattern actually uses instance variables
for the object state.) At least in my opinion. It's pretty difficult
to test, can't be extended and hard to use since it doesn't actually
have a constructor, just a "global state variable." Globals are bad.

public class StringUtils {

private static Locale locale;

private StringUtils() {}

public static void setLocale( Locale loc ) {
locale = loc;
}

public static String count( String s, int count ) {
...
}
...
}

This is pretty ugly design, imo. There's a few patterns it works for,
but they're not common. I don't think the OPs utility class would be a
good choice. Yes, I'm making an assumption here, but based on what he's
told us, I think it's the right assumption.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,150
Members
46,697
Latest member
AugustNabo

Latest Threads

Top