公共财产VS带吸气剂的私人财产? [英] Public property VS Private property with getter?

查看:164
本文介绍了公共财产VS带吸气剂的私人财产?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题困扰了我一段时间。可以直接进入的公共财产还是带有吸气剂的私人财产?哪一个更好/更正,为什么?

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?

推荐答案

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

Exposing fields directly is considered a bad practice.

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

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.

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

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).

相关

  • Are getters and setters poor design? Contradictory advice seen

这篇关于公共财产VS带吸气剂的私人财产?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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