公共财产 VS 带 getter 的私有财产?

发布于 2024-12-13 11:27:09 字数 63 浏览 2 评论 0原文

这个问题让我困惑了一段时间。可以直接访问的公共属性还是带有 getter 的私有属性?哪一个更好/正确,为什么?

This question has puzzled me for a while. A public property that can be accessed directly or a private property with getter? Which one is better/correct and why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

与风相奔跑 2024-12-20 11:27:09

具有 getter(以及可能的 setter)的私有属性被认为是正确的样式,因为将它们声明为公共并直接使用它们会损害封装原则。它可能导致的问题之一是您直接依赖于该字段的实现类型,这使得以后在需要时更难以更改。

此外,getter/setter 允许您向访问和变异的过程添加逻辑。您可以执行边界检查、输入验证、用默认值替换空值...

但是,在许多情况下,像大多数 JavaBeans 用法一样,getter/setter 所做的只不过是直接访问所做的事情。所以这整件事在 JavaBeans 环境中是有争议的。

我的意见?整个问题被严重夸大了,它引发的大量讨论已经消耗了足够的时间和键盘敲击来创建一个具有适当属性的全新 Java 语言规范。不要听信教条,做最适合你的事情,永远不要停止思考什么有意义、什么没有意义。如果每个人都接受上面的话,我们可能仍然在汇编中编码。

Private properties with getters (and possibly setters) are considered proper style since declaring them public and using them directly harms the principle of encapsulation. One of the issues it can cause is that you rely directly on the implementation type of the field, making it harder to change later if the need should arise.

Besides, getters/setters allow you to add logic to the process of accessing and mutating. You could perform boundary checks, input validation, substituting nulls with default values...

Then again, in many cases, like most JavaBeans usage, the getters/setters do nothing more than what you'd do with direct access. So this entire thing is kind of contested in the JavaBeans context.

My opinion? The entire matter is severely overstated and the amount of discussion it has sparked has eaten enough time and keyboard strokes to create an entirely new Java Language Spec with proper properties. Don't listen to dogma, do what works best for you and never stop thinking about what does and doesn't make sense. If everybody just accepted the words from above, we'd probably still be coding in assembly.

赏烟花じ飞满天 2024-12-20 11:27:09

直接公开字段被认为是一种不好的做法。

最好保持该字段私有,只公开 getter 和 setter。一个优点是您可以为 getter 和 setter 选择不同的访问级别,而字段只有一个访问级别。使用 getter 的另一个优点是它允许您在不更改类接口的情况下更改实现。

更好的是尽可能避免 getter 和 setter。相反,使用封装更高级别行为的方法。这是因为对象不应该篡改其他对象的内部状态(通过直接访问字段,或通过 getter 和 setter 间接访问)。

相关

Exposing fields directly is considered a bad practice.

It is better to keep the field private and only expose the getter and setter. One advantage is that you can choose different access levels for the getter and setter, whereas a field has only a single access level. Another advantage of using getters is that it allows you to change the implementation without changing the class interface.

Even better is to avoid getters and setters where possible. Instead use methods that encapsulate a higher-level behaviour. This is because objects shouldn't be tampering with other objects' internal state (either via directly accessing fields, or indirectly via getters and setters).

Related

岁月如刀 2024-12-20 11:27:09

一般来说,最好使用 getter 而不是公共字段,因为将字段设置为私有并公开 getter 可以防止调用者修改该字段,并允许您稍后更改实现而不更改接口。

此规则的一个例外是逻辑常量,对于逻辑常量,人们通常更喜欢公共静态最终字段:例如,Days.SATURDAY 而不是 days.getSaturday()。但是,如果该值附加到特定实例而不是类,或者可能会更改,或者通常感觉它不一定是通用常量,则私有字段/公共 getter 提供的灵活性使其更可取。

Generally it's preferred to use getters rather than public fields because making the field private and exposing a getter prevents callers from being able to modify the field, and allows you to change the implementation later without changing the interface.

One exception to this rule is for logical constants, for which people generally prefer public static final fields: Days.SATURDAY rather than days.getSaturday(), for instance. But if the value is attached to a particular instance rather than a class, or could ever change, or generally doesn't feel like it must be a universal constant, the flexibility provided by private field / public getter makes it preferable.

不必你懂 2024-12-20 11:27:09

尝试始终将字段声明为私有字段。假设您有一个银行帐户,并且您想提取一些现金:

public class BankAccountWithprivateField
{
    private Cash cash;

    // ...

    public void draw(int amount)
    {
        if(amount <= balance) cash.draw(amount);
        else sentMessage("Sorry your balance is less than what you request!");
    }
}

// ...

new BankAccountWithprivateField().draw(500);

在这里您提取的金额不能超过您的余额。

public class BankAccountWithPublicField
{
    public Cash cash;

    // ...
}

// ...

new BankAccountWithPublicField().cash.draw(1000000);

但在这里,你可以抽取 100 万美元;)

Try always to declare fields as private. Suppose you have a bank account and you want to draw some cash:

public class BankAccountWithprivateField
{
    private Cash cash;

    // ...

    public void draw(int amount)
    {
        if(amount <= balance) cash.draw(amount);
        else sentMessage("Sorry your balance is less than what you request!");
    }
}

// ...

new BankAccountWithprivateField().draw(500);

Here you cannot draw more than what you have in your balance.

public class BankAccountWithPublicField
{
    public Cash cash;

    // ...
}

// ...

new BankAccountWithPublicField().cash.draw(1000000);

But here, you can draw 1 million dollar ;)

离旧人 2024-12-20 11:27:09

保持字段私有可以防止其他类修改您的对象,想象一下继承模型,其中子级可以操作其父级的字段。

Keeping the field private prevents other classes from modifying your object, think of an inheritance model where a child can manipulate its parent's fields.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文