是否可以公开Immutable对象的状态? [英] Is it okay to expose the state of an Immutable object?

查看:120
本文介绍了是否可以公开Immutable对象的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近遇到了不可变对象的概念,我想知道控制状态访问的最佳实践。即使我的大脑的面向对象部分让我想看到公众成员的恐惧,我看到没有这样的技术问题:

Having come across the concept of immutable objects recently, I would like to know the best practices for controlling access to the state. Even though the object oriented part of my brain makes me want to cower in fear at the sight of public members, I see no technical issues with something like this:

public class Foo {
    public final int x;
    public final int y;

    public Foo( int x, int y) {
        this.x = x;
        this.y = y;
    }
}

我觉得将字段声明为 private 并为每个提供getter方法,但是当状态明确只读时,这似乎过于复杂。

I would feel more comfortable declaring the fields as private and providing getter methods for each but this seems overly complex when the state is explicitly read only.

什么是最好的提供对不可变对象状态的访问的实践?

What is the best practice for providing access to the state of an immutable object?

推荐答案

这完全取决于你将如何使用该对象。公共领域本身并不是邪恶的,将一切都公之于众是不好的。例如,java.awt.Point类使其x和y字段公开,并且它们甚至不是最终的。您的示例似乎很好地使用了公共字段,但是您可能不希望再公开另一个不可变对象的所有内部字段。没有包罗万象的规则。

It depends entirely on how you're going to use the object. Public fields aren't inherently evil, it's just bad to default everything to being public. For example the java.awt.Point class makes its x and y fields public, and they aren't even final. Your example seems like a fine use of public fields, but then again you might not want to expose all of the internal fields of another immutable object. There is no catch-all rule.

这篇关于是否可以公开Immutable对象的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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