javascript toString 实现的最佳标准样式是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3946529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:48:12  来源:igfitidea点击:

What is the best standard style for a toString implementation?

javaphpjavascriptactionscripttostring

提问by Nicole

We have a lot of objects for which we like to implement a simple toStringto output attributes of the object. Some of these attributes may be complex objects themselves.

我们有很多对象,我们喜欢实现一个简单toString的对象输出属性。其中一些属性本身可能是复杂的对象。

Is there any standard, or simply just a best practice for a style? I'm thinking something like:

是否有任何标准,或者只是一种风格的最佳实践?我在想这样的事情:

[SimpleClassName] { prop1:value, prop2:value }

In which case a nested value would look like:

在这种情况下,嵌套值将如下所示:

[SimpleClassName] { prop1:value, prop2:[NestedObject] { prop3:value}}

We are using Java but I find myself asking the same question in most languages!

我们正在使用 Java,但我发现自己在大多数语言中都在问同样的问题!

采纳答案by Wouter Coekaerts

Personally, I find the mix of []and {}not so easy to get an immediate view of the hierarchy.

就个人而言,我找到的混合[]{}不那么容易得到的层次的即时视图。

I like this format (and I've seen it being used in a number of places):

我喜欢这种格式(我已经看到它在很多地方被使用):

SimpleClassName[prop1=value, prop2=value]
SimpleClassName[prop1=value, prop2=NestedObject[prop3=value]]

There's also the possibility to add an identifier with @, for example the default stylefor the commons-langToStringBuilderdoes that (using its own example):

还可以添加带有 的标识符@,例如commons-lang的默认样式就是这样做的(使用它自己的示例):ToStringBuilder

Person@182f0db[name=John Doe,age=33,smoker=false]

回答by ColinD

I think the format produced by Guava's MoreObjects.toStringHelper()is pretty nice, but it's mainly just good to have some consistent format that you use:

我认为GuavaMoreObjects.toStringHelper()生成的格式非常好,但主要是使用一些一致的格式是好的:

public String toString() {
  return Objects.toStringHelper(this)
      .add("prop1", prop1)
      .add("prop2", prop2)
      .toString();
}

// Produces "SimpleClassName{prop1=foo, prop2=bar}"

回答by Brad Mace

json syntax seems to fit pretty well since it was designed specifically to represent complex objects as strings

json 语法似乎非常适合,因为它专门设计用于将复杂对象表示为字符串

Person = {
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": 
    {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021"
    },
    "phoneNumber": 
    [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567"
        }
    ]
}

回答by KrishPrabakar

Not a direct answer to the question, however below would be a time saver during initial development:

不是对问题的直接回答,但是在最初的开发过程中,以下内容可以节省时间:

Disclaimer: Apache Commons library is used.

免责声明:使用了 Apache Commons 库。

  1. Add a new Eclipse template called xreflectin Java > Editor > Templates; Add below into its patterntextarea:
  1. 添加一个新的名为Eclipse的模板xreflectJava > Editor > Templates; 将下面添加到它的模式textarea 中:
// ---------- template start ----------- //
${:import(org.apache.commons.lang.builder.EqualsBuilder,org.apache.commons.lang.builder.HashCodeBuilder,org.apache.commons.lang.builder.ReflectionToStringBuilder)}
/*
 * (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
 */
@Override
public boolean equals(
        final Object pObj) {
    return EqualsBuilder.reflectionEquals(this, pObj);
}

/*
 * (non-Javadoc)
 * @see java.lang.Object#toString()
 */
@Override
public String toString() {
    return ReflectionToStringBuilder.toString(this);
}

/*
 * (non-Javadoc)
 * @see java.lang.Object#hashCode()
 */
@Override
public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
}
// ---------- template end ----------- //
  1. Give OK, OK
  2. Just go to the end of a Java class, type xreflectand press Ctrl+ Spaceto autofill equals(), toString() and hashCode() methods automatically.
  1. OKOK
  2. 只需转到 Java 类的末尾,键入xreflect并按Ctrl+Space即可自动填充 equals()、toString() 和 hashCode() 方法。

回答by Stephen C

Is there any standard, or simply just a best practice for a style?

是否有任何标准,或者只是一种风格的最佳实践?

No. The "best" output for a toString()method is determined by what you want to use it for. Is it for serializing the object state in a form that allows it to be deserialized? Is it for creating debug messages? Is it for rendering the object for display to end-users?

否。方法的“最佳”输出toString()取决于您想将其用于什么目的。它是否用于以允许反序列化的形式序列化对象状态?是否用于创建调试消息?是否用于呈现对象以显示给最终用户?

If you want to develop an in-house style for your debug/logging toString()methods, that's fine. But unless there was a requirement for this, I wouldn't bother. IMO, it is effort that could better be spent elsewhere.

如果您想为您的调试/日志记录toString()方法开发一种内部风格,那很好。但除非有这个要求,否则我不会打扰。IMO,这种努力最好花在其他地方。

回答by zigdon

If your objects have something that might be useful as an identifier, I'd implement something like your second example:

如果您的对象有一些可能用作标识符的东西,我会实现类似于您的第二个示例的内容:

[SimpleClassName:id] { prop1:value, prop2:[NestedObject:id] { prop3:value }}

Where the idis whatever makes sense for that object to be an identifier - the name for the canonical Personobject, a primary key for an object from a database, etc.

凡是该id对象作为标识符有意义的地方 - 规范Person对象的名称,数据库中对象的主键等。

回答by Brad Mace

Since you asked about what other open source projects to, here's how jEdit does it, which is similar to Wouter's:

既然你问了其他什么开源项目,下面是 jEdit 是怎么做的,这类似于 Wouter 的:

BufferChanging[what=BUFFER_CHANGING,source=org.gjt.sp.jedit.EditPane[active,global]]

回答by rthrwht

check out phps print_r($obj, true) or also serialize() could work, dont know exactly for what its needed for. jsons is also a clean solution, especially if u want to import the data in javascript environbments

查看 phps print_r($obj, true) 或 serialize() 也可以工作,不知道它到底需要什么。jsons 也是一个干净的解决方案,特别是如果你想在 javascript 环境中导入数据