By Konstantin Pavlov
Returns string informative representation of an object.
Implementation in class Object returns
Is overridden to provide better object view in logs
Application business logic should not relay on a value
returned by this method
Long Living Objects
There are a limited number of long living objects
A set of objects may change at runtime
Used as Map keys
toString is called frequently (logging)
toString is called on the same instance multiple times
Long Living Objects. Solution
Since the instance set is not known at compile time, it is
not possible to use Enums.
Use object pool. You'll also be able to use identity
equals(==) and identity hashCode.
Evaluate and cache toString value in field of the object
It’s OK to use ToStringBuilder for evaluation
Keep toString value as short as possible
Short Living Objects
e.g. Data Transfer Objects (DTO)
toString usually called once
Short Living Objects. Receipts
Avoid using ToStringBuilder, no need to create extra
Use as little fields in toString as possible
It is not known yet how frequently object will be used
How long is lifetime?
Other Objects. Solution
Follow KISS principle, keep it simple!
Code must be readable and maintainable!
Don't spend much time on optimization on early phases
of the project
But don't put a performance bomb in your code. Try to
predict future object usage and don't write a code which
will definitely slow your application.