Re: why add toString() to a new class???
Tom Forsmo wrote:
www.pulpjava.com wrote:
This is simple a good design practice. Being able to print out the
state of a class, as opposed to just the memory location reference it
consumes, can be extremely helpful when debugging and logging.
You can add them when needed to debug the code. But as soon as you are
finished, it should be removed again.
I have heard the same thing about equals() as well. You should only add
these methods if they are an integral part of the functionality. E.g. if
you have a debug level log activity that requires printing object states
or you are doing a sort algorithm etc.
In my experience and opinion, there is only a few classes in a program
where I need to use these methods and then I only use it in certain
situations, perhaps for a shorter time period only.
There should not be left any code in the software which is not used in a
production environment, just because the programmers are lazy. It leads
to several potential problems, the code can be misused/forgotten about
(print statements /objects where the should be none in a prod
environment) and it can lead to it being more difficult to maintain the
code when garbage code is left lying.
It depends on the "scope" of the class. If you're writing
a one-purpose class intimately involved with the operation of one
application and with no possibility of re-use, Tom Forsmo's advice
makes sense. Unused code is just needless clutter, and nothing
will be harmed if it simply vanishes. (However, his warnings that
the code might be "misused" seem contradictory; how can anyone
"misuse" an unused method?)
However, if you're writing a class with the intent to re-use
it, or even if it's custom-tailored for a particular application
but you think the application might be extended or changed, Tom's
advice is less applicable. The fact that a method isn't used today
doesn't mean it won't be used tomorrow, and IMHO it's a good idea
to implement all the "core" methods sensibly. Tom mentions omitting
equals() -- well, if you think anyone might ever want to store class
instances in a Set, you should consider whether Object's equals()
suffices or not. If you implement the Comparable interface, you
should ponder whether it's better warn users of your compareTo()
that it is "inconsistent with equals" or just go ahead and implement
equals(). And when you implement equals(), it's all but mandatory
to do hashCode() at the same time.
If the history of software teaches anything, it's that systems
evolve in ways not anticipated by the original authors -- sometimes
smoothly, sometimes with unpleasant surprises. When writing a class,
including a clean and consistent implementation of "core" methods
like equals(), hashCode(), perhaps compareTo(), and, yes, toString()
can make the difference between assisting or inhibiting re-use.
--
Eric Sosman
esosman@acm-dot-org.invalid