lundi 3 août 2015

Changing mutable class into immutable

I'm facing an architecture decision which I need some help.

I'm creating a library that will be used by several clients. In this library I have a class named LibClass with a read-write property named aProperty and also class named LibManager which holds a reference to a Libclass instance. LibManager is responsible to update LibClass properties.

The clients can get the LibClass instance via a method on LibManager, let's call it getLibClassInstanceMethod. I don't want my clients to have access changing aProperty as this means that the clients can change my library model. I only want LibManager to have access changing aProperty.

How would you handle this situation where only inside the library you want to have full access over the properties (read+write), but from the client side, you only want read access to properties?

I've been contemplating with several solutions:

  • option 1

inside getLibClassInstanceMethod return deep copy of the object. Pros: I'm always sure that only the library has full access to the model. Cons: Memory consumption - each time I want to get the object, I need to clone it.

  • option 2

Making the LibClass immutable; Every time I want to make a change to the class properties, I need to create a new class and in the designated initializer(constructor) pass the new values. Pros: I make the class become immutable Cons: When class become bigger, it's a little weird to always re create classes just because one property changed.

  • option 3

Creating some sort of mutable/immutable pair like NSString/NSMutableString. Pros: Not sure Cons: For each class there's need to be two counterparts which double the number of classes.

I'm really not sure which path to go. What would you recommend?

Thanks

Aucun commentaire:

Enregistrer un commentaire