Re: Do I need private accessor methods?
Re: Do I need private accessor methods?
- Subject: Re: Do I need private accessor methods?
- From: "John C. Daub" <email@hidden>
- Date: Sat, 29 Apr 2006 10:26:25 -0500
- Thread-topic: Do I need private accessor methods?
on 4/28/06 4:32 PM, Eric Lin at email@hidden wrote:
> Do I need to create private accessor methods for my private instance
> variables?
The thread-safety issues others have discussed in this thread is certainly a
factor to consider. There's another way to look at it too.
When you set a variable directly, you are writing to implementation. When
you set a variable indirectly via an accessor, you are writing to the API.
Many times it's better to write to that API because it's an abstraction of
your implementation. Thus when your code evolves in the future, you may have
a better time of maintenance and implementing that evolution if all you have
to change is the one implementation of the accessor, not the multiples times
you might be using the implementation.
So in your example, let's say your code accesses that private variable 50
times. If you needed to change something about how that private variable
works (e.g. instead of being an int you change it to be an NSNumber), now
you have to go through your code and in all 50 places you work with that
variable you now have to deal with it as an NSNumber, which is not only a
pain to have to update 50 places in your code but is potentially a lot of
(redundant/replicated) code. If instead those 50 places went through an
accessor to the private variable, the API would remain the same (still takes
an int or returns an int) but the internals of that one method can change to
work with the int now as an NSNumber and the 50 places in code don't have to
change at all. Of course, this is theoretical as your particular needs may
vary from case to case, but it still illustrates a good point about why
accessors and writing to a more abstract API (as opposed to implementation)
can be good.
Same said for the threading... maybe you don't need thread-safety now, but
maybe you will in the future. Writing to a more abstract API could
facilitate and ease the changes.
Granted it can be a little bit of a pain to do this, but a little pain now
or a lot of pain later? Your choice. :-) Me, I try to look at the scope of
the code. If I'm just hacking something up, I really don't care and will
probably write to implementation because I know this is quick and dirty. If
I'm writing something that I expect will be around for a long time, could
evolve, could be publicly released, then I want it to be as well-behaved as
possible.
--
John C. Daub }:-)>=
<mailto:email@hidden> <http://www.hsoi.com/>
"Weak mind, weak fist. Strong mind, no need for fist."
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden