Subject: Proper way to access superclass instance variables
Message-ID: <1992Nov18.213742.493@afs.com>
Followup-To: comp.lang.objective-c
Sender: michael@afs.com
Reply-To: Michael_Pizolato@afs.com
Date: Wed, 18 Nov 1992 21:37:42 GMT
Lines: 81
A question of philosophy. Consider the following classes:
@interface Foo:Object
{
int value;
}
- setValue:(int)aValue;
- (int)value;
@end
@implementation Foo
- setValue:(int)aValue
{
value = aValue;
return self;
}
- (int)value
{
return value;
}
@end
@interface Bar:Foo
{
}
- mungValue;
- buggerValue;
@end
@implementation Bar
- mungValue
{
value += 2;
}
- buggerValue
{
[self setValue:[self value] + 2];
}
@end
Which method in Bar is better as far as accessing the instance variable 'value' from Foo? I say -buggerValue is better because if Foo is in a library I have obtained from some vendor, and that vendor changes the representation of 'value' and sends me an upgrade, my code still works. The method -mungValue could fail if the representation of 'value' changes. For example, if the Foo class changes to this:
@interface Foo:Object
{
double v1, v2;
}
- setValue:(int)aValue;
- (int)value;
@end
@implementation Foo
- setValue:(int)aValue
{
v1 = v2 = (double)aValue / (double)2.0;
return self;
}
- (int)value
{
return (int)(v1 + v2);
}
@end
There's not even a 'value' ivar anymore. I can't think of any good reason to access 'value' directly unless I have complete control over the implementation of the Foo class. Even if I do, it's painful to change every subclass of Foo that might use 'value' directly if I change Foo as above. Obviously, the above code is only a trivial and flawed example, but other, important data representations can change, and should change if we find better ways to do things. For encapsulation to work properly, we shou
ld bugger and not mung. ;-)
Any thoughts?
Thanx,
Michael
P.S. Given the conclusion that ivars should only ever be accessed through methods, it seems wrong that they appear in the @interface section. Of course we can't change it now, but does anyone know why they're there?