Hiding implementation is about abstractions!
To not expose the details of data, use:
Objects hide their data behind abstractions and expose functions that operate on that data.
Polymorphism
Procedural code | OO code | |
---|---|---|
Easy when.. | Add new functions (no need to change the existing data structure) | Add new classes (no need to change the existing functions) |
Hard when.. | Add new data structure (need to change all existing functions) | Add new functions (need to change all existing classes ) |
When to use | Want to add new functions instead of new types | Want to add new types than new functions |
the idea that everything is an object is a myth. Sometimes you do want simple data structures with procedures operating on them.
a module should not know about the innards of the objects it manipulates.
Another good resource to read:
https://betterprogramming.pub/demeters-law-don-t-talk-to-strangers-87bb4af11694
Chains of calls like this are generally considered to be sloppy style and should be avoided.
When ctxt
, Options
, and ScratchDir
are merely data structures without behaviors, the following codes do not violate the Law of Demeter:
half object and half data structure.
hybrids make it hard to add new functions but also make it hard to add new data structures. So should avoid using it.
When ctxt
, options
, and scratchDir
are objects with real behavior:
Quintessential form of a data structure (data transfer object, or DTO):
save
and find
Objects expose behavior and hide data; Data structures expose data and have no significant behavior.
More flexible when:
Objects | Data types and procedures | |
---|---|---|
Add new data types | V | |
Add new behaviors | V |
learn
clean code
test automation