Skip to content

Objects and Data Structures

There is a reason that we keep our variables private. We don’t want anyone else to depend on them.

We want to keep the freedom to change their type or implementation on a whim or an impulse.

Why, then, do so many programmers automatically add getters and setters to their objects, exposing their private variables as if they were public?

Data Abstraction

Data/Object Anti-Symmetry

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

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.

The complement is also true:

Procedural code makes it hard to add new data structures because all the functions must change. OO code makes it hard to add new functions because all the classes must change.

Mature programmers know that the idea that everything is an object is a myth. Sometimes you really do want simple data structures with procedures operating on them.

The Law of Demeter

  • The Law of Demeter tells about Loosely Coupling.
  • the Law of Demeter says that a method f of a class C should only call the methods of these:

  • C
  • An object created by f
  • An object passed as an argument to f
  • An object held in an instance variable of C
  • Train Wrecks

    Chains of calls like this are generally considered to be sloppy style and should be avoided.

    Hybrids Hiding Structure

    Data Transfer Objects:

    Eliminate writing setter and getter methods inside DTO.

    Active Record

    Don’t write business logic which contains DTO Related methods i.e save and find