班级何时应该使用自己的getter/setters而不是直接访问成员? [英] When should a class use its own getters/setters vs accessing the members directly?

查看:105
本文介绍了班级何时应该使用自己的getter/setters而不是直接访问成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Eclipse中生成setter和getter时,选项之一是在类中使用getter和setter,而不是直接访问类成员.这种级别的内部封装是有用的还是采取一个好主意太远了?

When generating setters and getters in Eclipse one of the options is to use the getters and setters within the class rather than accessing the class members directly. Is this level of class internal encapsulation useful or is it taking a good idea one step too far?

DUPE :推荐答案

如果您希望发生潜在的副作用-验证,日志记录等,我认为这是个好主意.(在C#中,我希望能够声明一个变量和属性,并说通过该属性访问该变量.)

I think it's a good idea if you want the potential side-effects to occur - validation, logging etc. (In C# I'd like to be able to declare a variable and property and say that the only access to the variable is through the property.)

有时候,您可能会发现您需要直接直接设置变量,因为您不想要.例如,您可能需要一起设置两个变量,并且"before"和"after"状态均有效,但是单独设置这两个属性会使验证失败.

Occasionally you may well find you need to set the variable directly precisely because you don't want the side-effects. For instance, you may need to set two variables together, and both the "before" and the "after" states are valid, but setting either property individually would make validation blow up.

这篇关于班级何时应该使用自己的getter/setters而不是直接访问成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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