mengdiwang / guava-libraries

Automatically exported from code.google.com/p/guava-libraries
Apache License 2.0
0 stars 0 forks source link

Objects.toString(obj) for null-safe toString() call #499

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
e.g.

    public static String toString(Object obj) {
        return toString(obj, "");
    }

    public static String toString(Object obj, String defaultStr) {
        return obj != null ? obj.toString() : defaultStr;
    }

Original issue reported on code.google.com by eric.j...@gmail.com on 17 Dec 2010 at 12:09

GoogleCodeExporter commented 9 years ago
I find the first version very counter-intuitive. Null returns the empty String? 
Why not let null return null?

public static String toString(Object obj) {
    return toString(obj, null);
}

Original comment by SeanPFl...@googlemail.com on 17 Dec 2010 at 8:37

GoogleCodeExporter commented 9 years ago
I suggested returning "" because that is what the corresponding method in 
Commons Lang does, but returning null may be more logical. The method could be 
combined with Strings.nullToEmpty when "" is desired.

However, looking at Strings.nullToEmpty, I wonder if this method could be 
generalized like so?

  public static String nullToEmpty(@Nullable Object object) {
    return (object == null) ? "" : object.toString();
  }

Original comment by eric.j...@gmail.com on 17 Dec 2010 at 6:39

GoogleCodeExporter commented 9 years ago
We don't think highly of null-safe libraries.  We are stuck with a few, but we 
don't wish to grow that set.

We've seen firsthand that if you make a reliance on nullable values easier, you 
just get more reliance on nullable values.  The spread of nullability through a 
codebase is a sickness.  It should instead be chopped off as close to the 
source as possible.

When you *have to* deal with null, it *should* be harder and uglier than not 
having to deal with it.

Original comment by kevinb@google.com on 19 Dec 2010 at 8:25

GoogleCodeExporter commented 9 years ago
This issue has been migrated to GitHub.

It can be found at https://github.com/google/guava/issues/<id>

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:15

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 3 Nov 2014 at 9:09