简体   繁体   中英

Why do we sometimes prefer having data structures over objects?

As Robert Martin's Clean Code said:

Objects hide their data behind abstractions and expose functions that operate on that data. Data structure expose their data and have no meaningful functions.

But he also mentioned that:

Procedural code (code using data structures) makes it easy to add new functions without changing the existing data structures. OO code, on the other hand, makes it easy to add new classes without changing existing functions.

and:

... Such hybrids make it hard to add new functions but also make it hard to add new data structures. They are the worst of both worlds. Avoid creating them.

Hybrid above means the hybrid between data structure and objects.

But it seems there is a conflict for data structure: the pros of using data structure is for adding functions easier, but for data structure we'd better never add functions in it. Then what's the point of having data structure? Eg DTO(data transfer object) are one of the examples of using data structure instead of using objects. And it's always a good practice to not add a lot of logic out of getters in it. -- But why?

You are misunderstanding what Uncle Bob said.

the pros of using data structure is for adding functions easier

No, it should be: the pros of separating data structures and functions is for adding functions easier.

When data structures and functions are separated, you can add a new function without breaking the old functions. In contrast, when data structures and functions are bundled into units like classes in OOP, adding a new function (method) will break all the old units/classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM