toString():用于调试还是用于人类? [英] toString(): for debugging or for humans?

查看:59
本文介绍了toString():用于调试还是用于人类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Address
{
  private enum Component
  {
    NUMBER,
    STREET,
    STATE,
    COUNTRY
  }

  private Map<Component, String> componentToValue = ...;
}

我希望我的课程包含两个方法:

I'd like my class to contain two methods:

  1. 一个表示每个地址组件的值(以便我可以调试是否出错).
  2. 一个以人类期望的形式返回地址的地址:"1600 Amphitheatre Parkway Mountain View,CA 94043".

Object.toString()的最佳做法是什么?它主要用于#1或#2吗?这些方法的命名是否有最佳实践?

What is the best-practice for Object.toString()? Is it primary meant for #1 or #2? Is there a best-practice for the naming of these methods?

推荐答案

您是否会以相同的方式在SMS消息和HTML页面中设置地址格式?您会用英语,法语和日语将其格式化吗?

Would you format an address the same way in a SMS message and in an HTML page? Would you format it the same way in English, French and Japanese?

如果否,那么您的答案是:表示不属于对象,而是属于显示对象的表示层.除非对象专门用于表示层,例如,如果它是HtmlI18nedAddress,则使用toString进行调试.

If no, then you have your answer : the presentation does not belong to the object, but to the presentation layer displaying the object. Unless the object is specifically made up for the presentation layer, for example if it is a HtmlI18nedAddress, use toString for debugging.

考虑DateSimpleDateFormat. Date包含状态,SimpleDateFormat返回多个表示形式.

Consider Date vs SimpleDateFormat. Date contains the state and SimpleDateFormat returns multiple representations.

这篇关于toString():用于调试还是用于人类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆