Imagine an ORM system, independent of language but let's assume PHP. Data is encapsulated in PHP objects and stored into and loaded from database.
Let us have a theoretical object "Person" with multiple addresses (so mapped to 2 tables in database), which can be added by a function.
Do NOT consider how access on data elements is done, it does not matter.
Some sample code:
$person = new Person();
$person->firstname = 'John';
$person->lastname = 'Doe';
// ...
// THIS IS IMPORTANT!
$person->save();
$person->addAddress([
'street' => '123, Foo Street',
'city' => 'New York',
// ...
]);
$person->addAddress([
'street' => '456, Bla Street',
'city' => 'Washington',
// ...
]);
What would you expect about how (when!) the addresses are saved?
Option 1: They are immediately saved after the call to addAddress()
Option 2: The call to addAddress() does only put it into the internal object, and they get saved only after an explit call to Person::save().
Option 3: Any further ideas are welcome.
I want to know which most people would prefer, which is more intuitive, if there are pros/cons for/against the different options. Maybe a killing argument?
Moreover, I suppose that Option 2 is harder to code (I know, using some framework can handle this, but assume that the database-object-mapping is much more complicate, so it must be done by hand), because it needs internal tracking of new entries, removed entries, changed entries etc.
Option 1 is easier to code, but I do not know if users (even if they are just in our company) will misunderstand this.
Person
responsible for its persistence in the database? Wouldn't this be better handled by a separate object? See en.wikipedia.org/wiki/Single_responsibility_principle