开发者

How to create write-once properties?

开发者 https://www.devze.com 2023-01-31 11:05 出处:网络
I\'m stuck with a general OOP problem, and can\'t find开发者_C百科 the right way to phrase my question.

I'm stuck with a general OOP problem, and can't find开发者_C百科 the right way to phrase my question.

I want to create a class that gives me an object which I can write to once, persist it to storage and then be unable to change the properties. (for example: invoice information - once written to storage, this should be immutable). Not all information is available immediately, during the lifecycle of the object, information is added.

What I'd like to avoid is having exceptions flying out of setters when trying to write, because it feels like you're offering a contract you don't intend to keep.

Here are some ideas I've considered so far:

  1. Pass in any write-information in the constructor. Constructor throws exception if the data is already present.
  2. Create multiple classes in an inheritance tree, with each class representing the entity at some stage of its lifecycle, with appropriate setters where needed. Add a colletive interface for all the read operations.
  3. Silently discarding any inappropriate writes.

My thoughts on these: 1. Makes the constructor highly unstable, generally a bad idea. 2. Explosion of complexity, and doesn't solve the problem completely (you can call the setter twice in a row, within the same request) 3. Easy, but same problem as with the exceptions; it's all a big deception towards your clients.

(Just FYI: I'm working in PHP5 at the moment - although I suspect this to be a generic problem)


Interesting problem. I think your best choice was #1, but I'm not sure I'd do it in the constructor. That way the client code can choose what it wants to do with the exception (suppress them, handle them, pass them up to the caller, etc...). And if you don't like exceptions, you could move the writing to a write() method that returns true if the write was successful and false otherwise.

0

精彩评论

暂无评论...
验证码 换一张
取 消