2

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? E.g. 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?

BSMP
  • 4,596
  • 8
  • 33
  • 44
laahaa
  • 327
  • 3
  • 12
  • 1
    Generally speaking, when you implement data structures in an object-oriented language, the data structures are going to be defined using classes and instances thereof will be objects. The terminology seems more C/C++ oriented, where you have a distinction between classes and structs as a language feature. – Ryan Pierce Williams Nov 05 '18 at 23:59
  • Note the conflict between objects and data structures is known as [the expression problem](https://stackoverflow.com/questions/3596366/what-is-the-expression-problem). – jaco0646 Dec 05 '18 at 18:59

1 Answers1

1

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.

Nghia Bui
  • 3,694
  • 14
  • 21
  • How do we separate the data structures and functions, especially in OO language like java? – laahaa Nov 03 '18 at 16:52
  • In “OO” languages you can still easily write nonOO code, just write classes without method, and write classes without properties using only static methods. – Nghia Bui Nov 04 '18 at 01:43
  • Rather than static methods, I would suggest composition: write objects that are composed of data structures and encapsulate them. This keeps data structures pure and simple, and prevents objects from being passed around as data structures themselves. – jaco0646 Nov 05 '18 at 14:55