Re: alternate pattern for object initializers
Re: alternate pattern for object initializers
- Subject: Re: alternate pattern for object initializers
- From: Kevin Grant <email@hidden>
- Date: Mon, 26 May 2008 02:28:16 -0500
The "init ivars and whatnot" could become several lines of assignments.
This multiplies across paranoid derived classes that override
initializers
and want to be explicit about initialization.
Both of those cases are made simpler if a highly specific initializer
exists, e.g. [self/super initWithX: andY: andZ: . . .
andProperties:nil].
It is also much safer to derive classes with "verbose" initializers,
because the method is given everything the caller wants. For instance,
the derived class may wish to allocate its own class Y, derived from X,
and set member "x" to it. If it calls [super init], what can the base
do? It has to waste time doing something like "x = [[X alloc] init]",
because it doesn't know "x" will be changed and it has no parameters to
receive a better value. Instead, the derived class should be able to
call [super initWithX:[[Y alloc] init]] (say), at which point the base
can assign "x" and do no alloc of its own.
Also, I wouldn't worry about one-liners. Some classes will always need
them, e.g. a read-only property won't have a setX method, but it could
have initWithX:.
Kevin G.
I am reasonably new to Cocoa. I do have the concept of a "designated
initializer" understood. However, I have begun to use an alternate
pattern. Before I get too far in my use of this approach, I thought
it best to check with the more experienced developers here to see if
my approach for doing "convenience" initializations is viable or
potentially problematic.
Since there may be lots of variations on initialization, I reverse
the pattern and have convenience initializers all call a common -init
- (id) init
{
self = [super init];
// init ivars and whatnot....
return self;
}
Convenience initializers for properties of the class invoke this
common -init, and then make adjustments:
- (id) initWithProperty:(PropertyClass*)propertyValue
{
if (self = [self init]) {
[self setProperty:propertyValue];
}
return self;
}
Of course, my invoking code could achieve the same ends with two
lines of code:
SomeClass *instance = [[SomeClass aloc] init];
[instance setProperty:propertyValue];
As I said, my pattern is just a convenience:
SomeClass *instance = [[SomeClass aloc]
initWithProperty:propertyValue];
So, I guess I have two questions here:
1) Is the convenience approach obfuscating (i.e., are the two lines
of code clearer to others who come in to work on the source)?
2) is my way of handling these convenience initializations viable?
Thanks.
_______________________________________________
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