DTO的迷思,以及“对象”和“数据结构”

“对象不应该有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.

你可能感兴趣的:(数据结构,bean,UI,XP,OO)