Objects and data structures

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  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

 

 

Functions

A function (method) is a the first line of organisation in any program.

Rules for making the functions communicate their intent:

  • not small but very small
  • do one thing – can you extract another method from it with a name that is not a restatement?
  •  use descriptive names
  • number of arguments: niladic, monadic,  dyadic, triadic (to avoid)
  • no side effects, no hidden things, do only what you promised in the name
  • do something (change the state of an object )or answer to something (return some information about the object), not both
  • use exceptions instead of error codes
  • Don’t Repeat Yourself – duplication, the root of all evil.