I'm a relatively new programmer, and not a single book that I'm using
has given concrete examples or underlying reasons as to why 'protecting'
your iVars by declaring them in @implementation rather than @interface
might be important or ever be important. Since each instance has their
own copy of the instance variables anyway, what is the potential for
doing something destructive?
I'm a relatively new programmer, and not a single book that I'm using
has given concrete examples or underlying reasons as to why
'protecting' your iVars by declaring them in @implementation rather
than @interface might be important or ever be important. Since each
instance has their own copy of the instance variables anyway, what is
the potential for doing something destructive?
Let's say you have a class called A which has a subclass B. In class
A, you have an iVar declared in @implementation named int x.
Therefore instances of class B (as a subclass of class A), do not
have direct access to x. If int x was declared in class A's
@interface section, the iVar int x would be public and could be
directly accessed by class B instances just as it can be by class A instances. Here's an example of a method in class B, the subclass:
// A method of class B (which is a subclass of A)
-(void) printVar
{
NSLog(@"The value of x is %d", x);
}
In this example, you'd get an error if x was declared in class A's implementation section, but no error if 'x' was public by being
declared in class A's interface section.
THE CORE QUESTION:
So, what is the reason for worrying about public vs private? There is
data encapsulation *already established anyway* solely due to the fact
that each instance has it's own set of instance variables. So, you
have that protection. For example if an object from the subclass (in
this example class B) had direct access to x, so what?
x.a = 42; // direct accesschar* mystr = xs->x.c;
x.c = "a string";
sc = [SomeClass new]; // OK inside internal A method , not anywhere else, though.Trouble is this seem reasonable when inside of A.h but carries no protection at runtime that the running program will assign A.sc a good SomeClass object.
data-processing ==>output-data>output->writer>output-filter>outputstream
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 406 |
Nodes: | 16 (2 / 14) |
Uptime: | 107:59:49 |
Calls: | 8,527 |
Calls today: | 6 |
Files: | 13,209 |
Messages: | 5,920,352 |