什么时候应该使用封装? [英] When should encapsulation be used?

查看:181
本文介绍了什么时候应该使用封装?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在完成Sun/Oracle的跟踪报告( http://docs.oracle. com/javase/tutorial/java/TOC.html ),并不断重申封装的重要性.

I am completing Sun/Oracle's Trail (http://docs.oracle.com/javase/tutorial/java/TOC.html) and it keeps reiterating the importance of encapsulation.

封装真的重要吗?我的意思是,如果我可能需要访问给定类字段的值,当我直接访问该字段时,为什么要通过一种方法来访问呢?由于无论如何都可以通过其对应的对象访问该字段,这到底会出错吗?

How important, really, is encapsulation? I mean, if I may need to access the value of a given class field, why would I do so through a method when I could just access the field directly? Since the field would be accessed through its corresponding object anyway, where could this really go wrong?

仅用于代码扩展性吗?换句话说,因为将来如果我决定我想以某种方式更改或消毒该字段,然后再返回该字段,我可以吗?

Is it just for code extensibility purposes? In other words, because that way in the future if I decide I want to somehow alter or sanitize the field before returning it I can?

我在寻找一个或两个例子比什么都重要.

I'm more looking for an example or two than anything.

推荐答案

封装不仅是对字段进行getter和setter的问题.

Encapsulation is not only a matter of making getter and setter for a field.

关于:

  • 验证(以及一致性)
  • 隐藏实现(编程为接口而不是实现)
  • 字母和二传手不必反映实际字段.可能会根据需要计算来计算值的字段的getter(甚至setter)
  • 隐藏复杂性:获取程序/设置程序可能会执行一些复杂的工作,而不仅仅是设置值
  • 高级:使用不同的实现/修改;如果您要使用公共字段,则在ORM框架中使用的惰性加载之类的模式将不起作用
  • Validation (and also consistency)
  • Hidding implementation (programming to an interface not an implementation)
  • Getters and setters don't have to reflect the acutal fields. There could be getters (and even setters) for fields which value is calculated on demand
  • Hide complexity: A getter/setter could peform something more complex than just setting a value
  • Advanced: Use of a diffrent implementation/modification; patterns like lazy loading which is used in ORM framework wouldn't work if you would use public fields

即使您说过需要访问给定类字段的值",您也不能确定此要求不会改变(因为它将在大多数时间).

Even if you as you said "need to access the value of a given class field" you can't be sure that this requirement won't change (cause it will most time).

这篇关于什么时候应该使用封装?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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