Question

    public String toString() {
        String info = "";
        String courseInfo = this.getCourseInfo();
        if("".equals(courseInfo)) {
            courseInfo = "None";
        }

        info += "--------------------------------------------------\n";
        info += "Student Name: " + this.name + "\n";
        info += "Student Address: " + this.address + "\n"; 
        info += "Student #: " + this.studentNumber + "\n";
        info += "Student Login ID: " + this.loginID + "\n";
        info += "Courses taken:" + "\n";
        info += courseInfo + "\n";
        info += "GPA: " + this.getGPA() + "\n";
        info += "--------------------------------------------------\n";

        return info;
    }

I was told that this is a bad toString method because it should be to output diagnostic information on one line, or a single literal value if that makes sense. I really don't understand. Should I just print all the instance variables and let the user decide what it is?

Was it helpful?

Solution

The problem is that this toString will produce a big block of code. Lets say it is called Student. If you wanted to log:

Student X linked to student Y because of Z.

Then the X and Y are going to become massive, and the whole line gets split out and unreadable.

You might have a "toFullDescription" or something method that looks like your current toString, but the toString should just have a few meaningful elements, probably just the name and Id inside curly braces.

OTHER TIPS

You put in toString any information that you consider relevant about the object. It will be of great importance for debugging purposes, like log files or debugging sessions in your IDE. Also, information in toString objects written to logs are useful for forensics when trying to identify problems in the application.

It is likely, though, that you will probably try to avoid putting sensitive information there (i.e. passwords, credit card numbers, etc).

I like to use the Apache Commons EqualsBuilder class for this kind of things. It has different formatting styles for your toString to make your life simpler.

For instance:

@Override
public String toString(){
 return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
              .append("orderId", this.orderId)
              .append("status", this.status)
              .append("type",this.type)
              .append("items", this.items)
              .toString();
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top