Re: Correct way to make mutable and immutable objects?
Re: Correct way to make mutable and immutable objects?
- Subject: Re: Correct way to make mutable and immutable objects?
- From: Quincey Morris <email@hidden>
- Date: Fri, 14 Dec 2012 18:21:46 -0800
On Dec 14, 2012, at 15:25 , Graham Cox <email@hidden> wrote:
> I have an abstract base class A and a mutable subclass AM. The class A owns a list of subsidiary objects but only the class AM has the methods for adding and removing these , which is what 'mutable' means for this class.
>
> There are a series of concrete subclasses B, C, D, etc which all set up the subsidiary objects in various configurations when they are initialized, but once done, the clients of these objects have no business mutating them so they need to be returned as the immutable variant. However, in order to work during setup they are in fact subclasses of AM. Is there a way to return them as if they were subclasses of A, so that the existence of the mutating methods is hidden from the client code?
Here are some possibilities:
1. Declare certain ivars @protected, allowing the subclass initializers to manipulate the subsidiary object collections directly.
2. Use a class-hierarchy-private initializer that passes the subsidiary object list up from the subclass to the base class, or a class-hierarchy-private method that replaces the default list, called during the subclass initializer.
3. Have each subclass initializer return an immutable copy of a mutable temporary object used for the initial part of the initialization.
4. Implement immutability as an internal class property, like NSArray etc. In that case, the class can be mutable for the duration of the initializer, then forced to be un-mutable. (The setters go in the base class, but they all start by explicitly testing the internal mutability property.)
Personally, I prefer #4, because it means the class implementation doesn't have to fight with the details of the class public interface. It just takes a bit more (very dull) code.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden