Java

本类阅读TOP10

·使用MyEclipse开发Struts框架的Hello World!(录像1)
·hibernate配置笔记
·AOP编程入门--Java篇
·linux下Tomcat 5.0.20 与 Apache 2 安装/集成/配置
·在win2003下整合了整合Tomcat5.5+ apache_2.0.53+ mod_jk_2.0.47.dll
·构建Linux下IDE环境--Eclipse篇
·Jsp 连接 mySQL、Oracle 数据库备忘(Windows平台)
·ASP、JSP、PHP 三种技术比较
·Tomcat5.5.9的安装配置
·AWT GUI 设计笔记(二)

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
DTO的迷思,以及“对象”和“数据结构”

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

“对象不应该有public的field,应该用getter/setter将field封装起来。”我们对于这个规则已经太熟悉,熟悉得完全忘记了它的由来。Uncle Bob提出了一个问题:完全用于传输数据的DTO是否需要getter/setter?实际上,在很多时候,DTO并不是一个“对象”(我们用这个词表示“数据与行为的组合体”),仅仅是一个“数据结构”——把数据从一个地方带到另一个地方。给“数据结构”加上getter/setter,从OOD的角度来说着实没什么价值。

但是我至少有两个理由反驳Uncle Bob的话。第一,有时DTO要对其中携带的数据加以组合或变换,给出适合UI层的形式,这时需要getter(甚至setter)的封装;第二,用jakarta-commons-beanutils工具可以很方便地在提供了Java Bean语意(即getter/setter)的对象之间复制属性。

Uncle Bob's Software Craftsmanship Corner

Oh No! DTO!

by Robert C. Martin
February 26, 2004
Summary
Should DTOs have public variables? Or should they have private variables with getters and setters?

I'm teaching an XP Immersion(TM) class this week. We are writing FitNesse tests as the acceptance tests for the application we are writing. One of the programmers was using a RowFixture. RowFixture requires the use of a DTO (Data Transfer Object) and insists that the variables be public. The programmer was aghast. "DTOs are always made with private variables and getters and setters!" he said. "Why?" I asked.

Why indeed? Has the religion of OO carried us so far away from common sense that we can't recognize a data structure when we see one? Why do we need to bloat our code with a bunch of useless getters and setters just to fulfill some dogmatic rule that nobody can adequately explain?

In my view OO programs contain two kinds of entities: Objects and Data Structures. Objects have private data and public methods. Data Structures have public data and no methods (or sometimes trivial navigational methods). There are very good reasons for keeping the variables in an object private. We want to know which functions can manipulate them. We want to protect the invariants of the object. We don't want others to depend on our details (DIP). On the other hand there is no good reason to use getters and setters in a data structure. A data structure is simply a packet of data, nothing more.




相关文章

相关软件