When is it desired to not implement toString() in Java?

后端 未结 24 2144
心在旅途
心在旅途 2020-12-10 00:45

A lead developer on my project has taken to referring to the project\'s toString() implementations as \"pure cruft\" and is looking to remove them from the code base.

<
24条回答
  •  情书的邮戳
    2020-12-10 01:04

    I figured I'd weigh in with a more modern perspective given that this question is now almost 10 years old.

    toString is obviously helpful for debugging - you need look no further than all of the other answers here which attest to that - but debugging information isn't business logic.

    Having a toString method in every single class is visual clutter which obscures the useful behaviour of the class. We also need to remember to maintain it - either manually or by regenerating the method from our IDE - every time we change the class fields.

    So what can we do to address these problems without removing the method altogether? The answer is to automatically generate it. Project Lombok's @ToString annotation can automatically generate a toString method for you at compile-time which includes any combination of fields that you choose.

    Basic sample usage:

    @ToString
    public class Foo {
        private int i = 0;
    }
    

    Which will become equivalent to the following at compile-time:

    public class Foo {
        private int i = 0;
    
        public String toString() {
            return "Foo(i=" + this.i + ")";
        }
    }
    

提交回复
热议问题