Re: How to organize an app (baffled with Accessor methods)
Re: How to organize an app (baffled with Accessor methods)
- Subject: Re: How to organize an app (baffled with Accessor methods)
- From: Joe Osborn <email@hidden>
- Date: Thu, 3 Oct 2002 07:18:12 -0500
@interface CalendarData : NSObject
{
NSMutableArray myDates;
}
- (NSMutableArray)myDates; // This is the accessor method for
// the array. The name should
remain
// the same as the array so you
can use
// keu-coding in the future.
- (NSCalendarDate)myDatesWithIndex:(NSNumber *)index; // for getting a
// single date.
- (void)changeDateAtIndex:(NSNumber *)index
value:(NSCalendarDate*)newDate;
// for changing a date at an index in the array
@end
I would say this is very, very, very, very, very bad. First of all,
it's bad form to have mutable instance variables- anybody could just
come along and change them as they please. Instead, make that
'myDates' array an NSArray, and in your set...: method, do:
-(void)setMyDates:(NSArray*)newDates
{
NSArray * oldDates = myDates;
myDates = [NSArray arrayWithArray:newDates];
[oldDates release];
}
You won't leak memory, and you won't open yourself up to code like...
[[someModel myDates] removeAllObjects];
or similarly malicious foreign code.
Furthermore, one shouldn't return collections from accessor
methods--see
http://www.c2.com/cgi/wiki?ReturnEnumerationsNotCollections -- although
in this case you may need it to be always in a particular order, in
which case you should return a copy of the array(though not necessarily
a copy of all the objects in it; use +[NSArray arrayWithArray:]).
-(NSEnumerator*)myDates
{
return [myDates objectEnumerator];
}
These are even a bit redundant if both used, but they'll insulate you
from making silly and hard-to-fix errors both in code and in design.
(Not to be overly nit-picky, but the standard for naming that third
method is more like -replace...with)
- (void)replaceMyDateAtIndex:(unsigned)index withDate:(NSCalendarDate
*)newDate
{
NSMutableArray * newMyDates = [NSMutableArray arrayWithArray:[[self
myDates] allObjects]]; //always use accessors, even internally to your
own class- this eases refactoring.
http://www.c2.com/cgi/wiki?WhatIsRefactoring
[newMyDates replaceObjectAtIndex:index withObject:newDate];
[self setMyDates:newMyDates];
}
Forcing the set...: method to be the only way to modify your array
instance variable means you can do any verification you want-- you have
full, 100% control over people mucking about with your objects.
including yourself.
--joie
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.