不可变类型:公共最终字段与getter [英] Immutable Type: public final fields vs. getter

查看:77
本文介绍了不可变类型:公共最终字段与getter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个小的Container-Class来存储一些应该是不可变的字符串。由于String本身是一个不可变类型,我想到了类似的东西:

I need a small Container-Class for storing some Strings which should be immutable. As String itself is an immutable type, I thought of something like that:

public final class Immu
{
  public final String foo;
  public final String bar;

  public Immu(final String foo, final String bar)
  {
    this.foo = foo;
    this.bar = bar;
  }
}

很多人似乎反对使用公共字段改用Getters。恕我直言,在这种情况下,这只是样板文件,因为String本身是不可变的。

Many people seem to object using public fields at all and use Getters instead. IMHO this would be just boilerplate in this case, because String itself is immutable.

我可能在这个问题上缺少其他想法吗?

Other thoughts I may be missing on this one?

推荐答案

我会做你认为最简单和最清楚的事情。如果您有一个仅由有限数量的类使用的数据值类。特别是一个包本地类。然后我会避免使用getter / setter并使用包本地或公共字段。

I would do what you believe is simplest and clearest. If you have a data value class which is only used by a restricted number of classes. esp a package local class. then I would avoid getter/setters and use package local or public fields.

如果你有一个你希望其他模块/开发人员使用的类,请使用getter / setter从长远来看,模型可能是一种更安全的方法。

If you have a class which you expect other modules/developers to use, following a getter/setter model may be a safer approach in the long run.

这篇关于不可变类型:公共最终字段与getter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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