Re: Subclassing with more restrictive initializers
Re: Subclassing with more restrictive initializers
- Subject: Re: Subclassing with more restrictive initializers
- From: Michael Ash <email@hidden>
- Date: Wed, 25 Feb 2009 11:52:36 -0500
On Wed, Feb 25, 2009 at 11:39 AM, Andy Klepack
<email@hidden> wrote:
> To make things more concrete (this isn't the actual case I've run into, but it's a similar, simpler illustration) consider a class "File" that has an initializer 'initWithPath:' and behavior 'delete', 'rename', etc. Then consider wanting to implement a class like 'PreferenceFile' that should only refer to files in the Preferences directory and thus has an 'initWithName:" initializer. "initWithPath" provides too much parameterization since it could refer to any file outside of the Preferences directory. Finally, the PreferenceFile class should have the same behavior as File and add some of its own (e.g. "setPrefValue:ForKey:").
>
> Should PreferenceFile inherit from File despite the initialize behavior being undesirable? Is composition somehow more appropriate? Is this confusion the result of thinking about the problem from the wrong direction?
I'd say that there are three reasonable approaches, depending on your
tolerance for complexity.
1) Subclass and stick a note somewhere that says, "Don't call
initWithPath:". Alternatively, *allow* initWithPath: too. This would
give you a preferences file in some other location.
2) Have the note that says "Don't call initWithPath:", *and* override
it to fail in some obvious fashion so that you can catch the places
where you've used it inadvertently.
3) Don't subclass. Have a has-a relationship with the File class.
Either have a getter that returns the File instance or use message
forwarding to make it look like you have all those File methods you
really don't.
My personal preference would be for #1. Convention is sufficient for
this sort of thing, no need to enforce it.
Mike
_______________________________________________
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