Skip to main content
GameDev.net gamedev.net
🔒 Locked

Class question:

Started by Crazyfool Aug 30, 2006 at 3:42 AM 0 replies 250+ views
Original Post
Crazyfool
Crazyfool
I have read all over that having your variables kept private in a class, and having 1 method for accessing, and 1 method for assigning is the best way. I would like to know why. Ive heard that it prevents errors in assignment, but couldnt you just do the same thing when you call setX(7) when you meant to type 8? The reason I ask is because in my RPG, I have TONS of variables within all the classes, and I was just wondering what is generally thought on this. Thanks
Zakwayda
Zakwayda
Quote:
Original post by Crazyfool
I have read all over that having your variables kept private in a class, and having 1 method for accessing, and 1 method for assigning is the best way. I would like to know why.

Ive heard that it prevents errors in assignment, but couldnt you just do the same thing when you call setX(7) when you meant to type 8?

The reason I ask is because in my RPG, I have TONS of variables within all the classes, and I was just wondering what is generally thought on this.
There was an extensive discussion on encapsulation recently; you can find it here. You should be able to find some useful info there.

As to your specific question, having 'getters' and 'setters' which do nothing more than 'get' and 'set' is similar in effect to making the corresponding member variables public (as you note). Usually though such functions have additional behavior (such as enforcing invariants or maintaining internal relationships), or, better yet, are replaced by more expressive behavior-oriented functions. (I think you'll find some good examples in the aforementioned thread...)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.