Sign in to follow this  
StoneMask

Do I need accessors and mutators for every class variable?

Recommended Posts

I understand the importance of keeping some data members from being accidentally manipulated outside class functions, but say I have a class object that's full of variables I need to check up on all the time, like the player in a video game. Is it really worth it to make the program jump control between those functions all the time? What are the criteria for a variable that's worth making an accessor/mutator function? Because so far, this is what my character's header looks like:

[spoiler][code]/* mutators */
void AddLevel (short alteration);
void AddHealth (short alteration);
void AddExP (short alteration);
void AddKeys (short alteration);
void AddTorches(short alteration);
void AddGems (short alteration);
void SetFacing (short alteration);
void SetExP (short alteration);
void SetPosX (short alteration);
void SetPosY (short alteration);
void SetIsHurt (short posX, short posY, bool isBoss);
void SetInFort (bool alteration);
void SetInShop (bool alteration);
void SetInSpace (bool alteration);
void SetFasT (bool alteration);
void SetGoldWhale(bool alteration);
void SetWin ();
void SetmFufni();
void SetName ();
/* accessors */
short GetLevel();
short GetHealth();
short GetExP();
short GetKeys();
short GetTorches();
short GetGems();
string GetName();
short GetFacing();
short GetPosX();
short GetPosY();
bool GetTorch();
short GetTorchX();
short GetTorchY();
char GetInFront();
bool GetInFort();
bool GetInShop();
bool GetInSpace();
bool GetFasT();
bool GetIsHurt();
bool GetSetting();
bool GetWin();
COORD GetPos();
[/code][/spoiler]

I'm running out of stuff to name these things, and sometimes I have to work around just naming it something I think is clear enough. Edited by StoneMask

Share this post


Link to post
Share on other sites
What do you mean? Wouldn't that mean just any variable that's actually changed? How do you define arbitrary when modifying something? Or breaking the class from the outside, for that matter? Edited by StoneMask

Share this post


Link to post
Share on other sites
Could you give me an example of something that would need subdividing into multiple classes, and how to implement it so you can still access all the information of the other class? Edited by StoneMask

Share this post


Link to post
Share on other sites
Getting a bit away from your specific question, I'd caution that part of the problem is that you're beginning to have a rather monolithic, unfocused class.

It's difficult to say without knowing more about the design of the game itself, but the impression that the accessor/mutator names give me is that some of them could stand to be combined into their own class (For example: posX, PosY, and [maybe] Direction might become a class) and others either seem to be misplaced (InFront, InFort, InShop, InSpace) and/or might indicate some kind related state that could be expressed as an enumeration (if states are mutually exclusive or have limited but well-known combinations) or a bitfield (if states can be combined more freely).

Still others might be better solved in a much more general fashion, for example you have a number of variables that seem to track inventory -- if the variety of available inventory items is small this approach may be fine, but if the varieties grow to more than a couple of handfuls, you might want to look into creating an inventory object that holds the actual items, and having this "player" class have an inventory (either directly, or by owning a unique key within a shared inventory system). In short, as you add more variety of items, you tend to want something that starts to look more and more like a database, rather than an ad-hoc collection of values. You can do stats similarly.

Basically, try to think about the different contexts in which you currently plan to access your "player" class, and see how the data naturally groups together -- for example, its unlikely that a single context would care about the player position *and* the contents of their inventory simultaneously, in a well-designed system.

Share this post


Link to post
Share on other sites
I made this project under a deadline and I just kind of added stuff and didn't plan anything out. The state of where the character is in the environment could definitely be an enumeration, now that I think about it. I have other enumerations in the class.

The character's inventory really only has two things in it. The game is very simple.

So you're all recommending that I make some of these things structs or classes and have the getters of my player class just return one of the values depending on the states in those structs or classes? As a cleanliness question, would I want to put the classes that are used solely for other classes in their own .h/.cpp files?

Share this post


Link to post
Share on other sites
How do you mean 'used solely for other classes'? Like you have class A and class B and class A is the only class that uses class B? If that's what you mean then one option is to nest class B within class A. Here's some more [url="http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr061.htm"]information[/url].

Share this post


Link to post
Share on other sites
I myself like to make setters and getters but the way from MichaBen:
[quote]Personally I try to avoid setters that refer to a specific variable, as that would mean the object who calls it has to know how this class works internally. Instead, I prefer to have functions that invoke a specific state change or give me the information I need.[/quote]
is really a great way.
You should know your class and focus it only on the specific tasks.
But sometimes there is no time or you have a lazy phase (never ever listen to this phase, please!), then can you make your class properties (variables) public, but only if it is something like a data storage (old-fashioned structs).
Example:
[CODE]
class A
{
/*Very much variables*/
int Variable1;
int Variable2;
int Variable3;
...
}
/*You want to return more than one variable, therefore use a class.*/
A foo(int i)
{
A a;
a.Variable1 = sin(i*PI);
a.Variable2 = cos(i*PI);
a.Variable3 = sin(i*PI)*cos(i*PI);
/*And so on...*/
return a;
}
[/CODE]
Class "A" will be never used somewhere else.

This above looks sometimes useful and time saving, right?

[b]Forget it![/b] It is a mess. You can never be really sure that class "A" will not be used somewhere else!
This example above is a design mistake. Give yourself time and make some design. Use setter/getter or better real members (like these from MichaBen).
You will be in the safer site and will not have a headache or acute laziness later.

This failure happened often to me years ago.
Of couse the example is not wrong, but for me it's just disgusting. Use it if you like it. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img] I do not.

Share this post


Link to post
Share on other sites
[quote name='ApochPiQ' timestamp='1343412734' post='4963719']
...good information...
[/quote]
I'd just like to point out the fact that you have too many damn points. Ignore the fact that I've upvoted you a few times already :P

Share this post


Link to post
Share on other sites
Many of the variables are being accessed by code in my main.cpp, where the program determines what to do based on what I get from the class object in terms of information.

Share this post


Link to post
Share on other sites
[quote name='StoneMask' timestamp='1343430305' post='4963792']
Many of the variables are being accessed by code in my main.cpp, where the program determines what to do based on what I get from the class object in terms of information.
[/quote]

Thats probably your problem, you're trying to force an OO structure (a class) on a non OO design which is why you need so many accessors and mutators.

a class should have methods that do things with the class instance and possibly a few methods to inspect the state of the object.

For example, you have AddLevel and AddXP methods. atleast one of those is redundant, possibly both.

consider this:

player.attack(monster[6]);

if the monster dies the player can get the xp value from the monster directly, add it to its current XP and if necessary increase the level, no other class has to be able to do this.
Other classes might want to read the current level of the player object though (to be able to show it in for example the UI) and you could possibly want an addXP method if you need to trigger xp gains without the player doing anything. (I can't think of a single case where you'd want to do that though, xp gains are almost always the result of an action performed by the player object)

Also, OO is not the only or necessarily the best way to do things, if you prefer a different approach feel free to use it, but don't try to force OO structures on non OO code, it gets very painful very quickly. (if you just want to group data logically structs are a far better match than classes) Edited by SimonForsman

Share this post


Link to post
Share on other sites
[quote name='SimonForsman' timestamp='1343431104' post='4963797']
Also, OO is not the only or necessarily the best way to do things, if you prefer a different approach feel free to use it, but don't try to force OO structures on non OO code, it gets very painful very quickly. (if you just want to group data l[b]ogically structs are a far better match[/b] than classes)
[/quote]
I was just thinking this and was going to post it. But since you have already mentioned, I'll just reiterate by quoting you. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img] Edited by Alpha_ProgDes

Share this post


Link to post
Share on other sites
[quote name='darookie' timestamp='1343472434' post='4963909']
While OO-purists would point out that having public class variables is a sign of bad design, I tend to think more practically. C++ is a multi-paradigm language for a reason and I personally see no point in debates over stylistics.

Oops, I just noticed that Alpha_ProgDes wrote exactly this Posted Image
[/quote]
But yours has more detail and a good point about C++. Edited by Alpha_ProgDes

Share this post


Link to post
Share on other sites
So when you're saying it should be more exclusively OO or not, you're saying my functions should either take place within the class object or in the main code? And how do I return a state to the main function when the struct or class only exists in my player's struct or class? Is it a simple Player::(struct) temp? I could probably find this out on my own, but I want to cover my bases, as I don't quite know what is poor practice yet. I have, however, figured out that it's probably easier to have a collide function that checks what the player collides with, then make appropriate alterations. Like say, colliding with nothing will cause me to move forward, and colliding with a heart will increase health. Most stat alterations happen through collisions. The only exceptions would be when I buy things from a shop, which uses external code from the class. How would I handle that? Would I just add in an addHealth function anyway?

Also, since the inventory is really only one thing, followed by two gained abilities, do you think a bool array would be good? Like, position one is whether or not fast travel is enabled, position two is whether or not I have a certain ability, etc.? It seems simpler than going with a vector or something, and even though I know it's negligible in terms of memory, I'm a somewhat minimalistic person.

I have more questions, but these are the more immediate ones. I was re-reading through the responses since I've cleared my mind of all the complicated stuff and looked through everything with fresh eyes, so to speak.
Thanks for your help.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this