托斯特林方法中应包括的内容,什么不应该包括在内


    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;
    }

我被告知这是一种不良的to污方法,因为它应该是在一行上输出诊断信息,或者如果有意义的话,则应该是单个字面价值。我真的不明白。我应该只打印所有实例变量,然后让用户决定它是什么?

问题在于,此tostring将产生很大的代码。假设它被称为学生。如果您想登录:

Student X linked to student Y because of Z.

然后x和y将变得庞大,整个线被拆分和不可读。

您可能有一个" tofulldescription"或看起来像您当前的tostring的方法,但是ToString应该只有一些有意义的元素,可能只是卷曲内部的名称和ID。

您将您认为与对象相关的任何信息放入tostrth。对于调试目的,例如日志文件或IDE中的调试会话,这将非常重要。此外,在尝试识别应用程序中的问题时,写入日志的tostring对象中的信息对于取证很有用。

不过,您可能会尝试避免将敏感信息放在那里(即密码,信用卡号等)。

我喜欢将Apache Commons等价类用于这种事情。它具有不同的格式风格,可以使您的生活更简单。

例如:

@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();
 }

相关内容

最新更新