Accessor Functions, are they really used?

Started by
2 comments, last by Daishim 22 years, 8 months ago
Are accessor functions really widely used to get variable data from a class? Other than protecting the variables I don''t see any other use for them, could someone maybe enlighten me?

I know only that which I know, but I do not know what I know.
Advertisement
I use them religiously ''cos I come from a Java background. Almost all my member variables are private with accessors. The only good thing about them is that extra layer of protection. But the reason to use them from the start is forward thinking - it''s a bitch to change code to use a function when everything is directly accessing the variable & one day you realise that that variable should NEVER be decremented below -50, hmmm.

Just my thoughts

Brad
As far as I know the only purpose is protecting the variables. I''m sort of on the fence with this one. If I''m the only person who''s ever going to use the class, why should I bother protecting the variables? But in the end I do it anyways. Personally, I think it makes the code a little clearer.

If there''s another reason for this I''d be interested to know what it is.
Daishi, you nailed it right on the head. all accessors do is protect data. if you are following good OO design standards, they are a must. brad illustrated it nicely. for example, you have an object that keeps track of a number. for purposes of output, you only need it to be precise to the nearest integer. later you determine that due to mathematical roundoff error, you want to keep track of it as a double. instead of recasting it every time you need the value in your program, you just write the accessor function to cast it once and it is taken care of every where else. no changes to your original code needed. otherwise, for purposes of speed (not sure how much given todays compilers), you could make everything public. but if you have no problems keeping all your variables straight, you are justified in thinking that they have no practical use. just my opinion.

cyn

This topic is closed to new replies.

Advertisement