Search code examples
javatostringpojoapache-stringutils

toString() in POJO Class


Is it required to add toString() in all the POJO classes?

Its kind of a very basic question but I am worried about writing a piece of code in each n every POJO classes.

I have followed many java sources and I found a common things in those POJO classes-

@Override
    public String toString() {
        return StringUtil.toDetailString(this);
    }

Is it required for serialisation or helps in performance improvement or something else?


Solution

  • From my experience I prefer to add a toString() method in all POJO classes because it helps if you want to print the current state of an instance, using a logging framework or not.

    The default toString() method outputs a string formed from:

    getClass().getName() + '@' + Integer.toHexString(hashCode()).

    That is not useful 99.8% of the time. Usually you want to read the value of your class attributes. For that you need to override toString().

    You never know when you want to see its state outside of a debugging framework.

    If you/someone else logs your instance to see what it contains, if you don't override the toString() the output will only be the name and hash; that is not very informative.

    The performance aspect is not influenced at all, neither is serialization (using a serious framework) as far as I know of.

    I recommend using the source generation feature of your IDE to generate toString() methods. It is fast and gives you more control.