A class should not push its variables out through getters and setters. It should expose abstract interfaces that allows its users to manipulate the essence of the data without having to know its implementation. We want to express data in abstract terms.
Procedural code (code using data structures) makes it easy to add new functions without changing the existing data structures. Object oriented code makes it easy to add new classes without changing existing functions.
Not everything is an object.
The Law of Demeter – a module should not know about the innards of the objects it manipulates. A method f of a class C should call only 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
Talk to friends, not to strangers.
Data Transfer Objects – a very useful structure with public variables and no functions used especially when communicating with database which often become the first in series of translatio stages that convert raw data in a database into objects in the application code.
Active Records – a special form of DTO with navigational methods like save or find and are direct translations from database tables.
Objects expose behavior and hide data making it easy to add new kinds of object without changing existing behaviors. It also hard to add new behaviors to existing objects.
Data structures exposes data and have no significant behavior. That makes it easy to add new behaviors to existing data structures but makes it hard to add new data structures to existing functions.
Choose the right approach:
- objects – the flexibility to add new data types
- data structure – the flexibility to add new behaviors