views:

60

answers:

3

I want to give my previous question a second chance since I think I have chosen a bad example.

The question is how I should deal with situations where an object still can change after I have used it to do something and the new state is relevant for what is being done.

Example in pseudo-code:

class Book
    method 'addChapter': adds a chapter

class Person
    method 'readBook': read an object of class Book

Now when I ask the person the read a book, at least in PHP where the object will be passed by reference, the book object can still change. I could insert a chapter between chapter 3 and 4 while the person is already reading chapter 6. How can I deal with these kind of situations?

+3  A: 

Maybe notifying the person that the book has changed? You can do it with events (not sure how events work in PHP). Another way is to implement the Observer/Observable pattern.

Carles
+1 for the observer (a.k.a publish-subscribe) pattern
orip
A: 

Seems to me you are attempting to perform concurrent tasks. You might want to consider serializing activities to your objects instead, certainly in the case of PHP.

jldupont
+2  A: 

Any of the above answers is good for a good solution depending on your business demand.

You asked "How should I deal with situations..." it depends:

Is adding a chapter after you already shipped a book to the user legal? if not- you should throw an exception (I do not know if PHP supports exceptions, but anyway- you should treat is as an error situation).

Another solution would be to make sure that you expose and object that is already whole and does not expect changes to be made to it- this may be a valid solution especially if your decision to enable this kind of 'streaming' is performance oriented but you don't have real evidence that that this section is a performance bottleneck.

Now lets sat the addition of a new chapter is legal.

Do you want the change to be known to existing client or only to new clients?

If the former- you should implement some kind of notification logic (one of the suggeted forms is the a publisher/subscriber pattern, but there are others).

If the letter- you should make your book object immutable, so mutating operations will not be seen in existing clients, rather they would create an entirely new book the would be passed to new clients (Persons).

I could go on and on, But I suggest that next time you elaborate more on the exact problem you are trying to solve, since as you can see- the same problem can have a different solution in different domains.

Vitaliy