View more

View more

View more

### Image of the Day Submit

IOTD | Top Screenshots

### The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.

# Do I need accessors and mutators for every class variable?

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

19 replies to this topic

### #1Akashi  Members

Posted 27 July 2012 - 10:43 AM

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

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, 27 July 2012 - 10:47 AM.

### #2ApochPiQ  Moderators

Posted 27 July 2012 - 10:51 AM

POPULAR

Empty accessors and mutators are a code smell.

If you need to do some logic that ensures that the class's invariants are upheld when changing a variable, go ahead and wrap it in this way. Otherwise, if modifying the variable arbitrarily can't break the class from the outside, just use public member data.
Wielder of the Sacred Wands

### #3Akashi  Members

Posted 27 July 2012 - 11:10 AM

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, 27 July 2012 - 11:10 AM.

### #4MichaBen  Members

Posted 27 July 2012 - 11:15 AM

POPULAR

Performance is not really an issue, specially if you pass variables bigger then a single datatype as const reference, getters will usually be inlined by the compiler and will compile into the same code as if you would access the variable. However, you shouldn't have classes with tons of setters and getters, having to many of them is probably a sign your class has to many responsibilities and needs to be split into multiple classes, or that it has to little responsibilities (which is possible as well if you are using your class as a struct rather then object). 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. Just like in real life, if you buy a plane ticket you ask for a plane ticket to the destination you want to go, you don't ask the person behind the desk to take form C13, put it in the printer, type in your destionation and hit print. Basically you tell what you want to be done, not how you want it to be done.

### #5Akashi  Members

Posted 27 July 2012 - 11:33 AM

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, 27 July 2012 - 11:34 AM.

### #6Ravyne  Members

Posted 27 July 2012 - 11:36 AM

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.

throw table_exception("(ノ ゜Д゜)ノ ︵ ┻━┻");

### #7Akashi  Members

Posted 27 July 2012 - 11:44 AM

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?

### #8nobodynews  Members

Posted 27 July 2012 - 11:50 AM

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 information.

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

### #9ApochPiQ  Moderators

Posted 27 July 2012 - 12:12 PM

POPULAR

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?

For example, suppose you have a class that represents a book that you can write in. That class has a variable "NumWrittenPages" which tells you how many pages have been written in. It also has a function "WriteOnPage" which increments the NumWrittenPages variable.

Now; suppose some other code just goes and sets NumWrittenPages to some new number, without calling WriteOnPage. This would "break" the class in the sense that the object no longer correctly reflects reality. If WriteOnPage depends on the value of NumWrittenPages, this is probably a bug waiting to happen.

In that case, you want to use an accessor for NumWrittenPages, but not provide a mutator.

Or you might have a NormalizedVector class, which expects that its length is always 1. Modifying its x, y, and z coordinates directly is a recipe for disaster, because external code can make the length change to anything. So you wouldn't make them public. However, you might want to support setting the vector up all at once, such as Set(x, y, z). In that case, you simply implement Set() so that it re-normalizes the vector regardless of what the input numbers are. This ensures that the class invariant (i.e. the vector is length 1) is never violated.

In cases like this where you need to ensure something doesn't break when you set new variable values, mutators are OK. If you don't need limitations like that, just use public member variables.
Wielder of the Sacred Wands

### #10Narf the Mouse  Members

Posted 27 July 2012 - 12:59 PM

Here's an idea for you: "void AddToCharacteristic( CharacteristicType type, int value );"

### #11omercan  Members

Posted 27 July 2012 - 01:00 PM

I myself like to make setters and getters but the way from MichaBen:

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.

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:
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;
}

Class "A" will be never used somewhere else.

This above looks sometimes useful and time saving, right?

Forget it! 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. I do not.
I have a blog: omercan1993.wordpress.com look there for more content
And I also do some art: omercan1993.deviantart.com
And whats about the Pear3DEngine? Never heard of it? Go and look!
Yeah, and currently I do this: SimuWorld

PS: Please look at this poll on my blog about scripting languages: A opinion poll about scripting language

### #12Alpheus  GDNet+

Posted 27 July 2012 - 03:16 PM

...good information...

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
External Articulation of Concepts Materializes Innate Knowledge of One's Craft and Science

Super Mario Bros clone tutorial written in XNA 4.0 [MonoGame, ANX, and MonoXNA] by Scott Haley

If you have found any of the posts helpful, please show your appreciation by clicking the up arrow on those posts

Spoiler

### #13Alpheus  GDNet+

Posted 27 July 2012 - 03:21 PM

POPULAR

So the short answer is no, you do not. First you determine which variables really need to be accessed by objects outside of that class. Then through some poking and prodding, you determine which variables are read-only and therefore need accessors. And which variables will need to updated and therefore need mutators. But if you are doing things like:
[source lang="csharp"]public int getScore(){ return this.playerScore;}public int setScore(int points){ this.playerScore = points; return this.playerScore;}[/source]

Then just do this:
[source lang="csharp"]public int playerScore;[/source]

Edited by Alpha_ProgDes, 27 July 2012 - 06:02 PM.

External Articulation of Concepts Materializes Innate Knowledge of One's Craft and Science

Super Mario Bros clone tutorial written in XNA 4.0 [MonoGame, ANX, and MonoXNA] by Scott Haley

If you have found any of the posts helpful, please show your appreciation by clicking the up arrow on those posts

Spoiler

### #14Akashi  Members

Posted 27 July 2012 - 05:05 PM

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.

### #15SimonForsman  Members

Posted 27 July 2012 - 05:18 PM

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.

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, 27 July 2012 - 05:26 PM.

I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!

### #16darookie  Members

Posted 28 July 2012 - 04:47 AM

POPULAR

I won't go into any design/architecture points because that wasn't your question, so here's a little check-list that might be worth looking at:
• is the class variable used outside the class it is defined in?
No: make it private. End of list.
• Is the class variable only used by derived classes?
Yes: make it protected
• Is the class variable only used for read access outside the class?
Yes: make it private and declare a read-only accessor. End of list
• Are there any constraints on the contents of the variable, i.e. range checks, consistency issues, etc.?
No: make the variable public. End of list.
Yes: make the variable private and declare a mutator that checks for/enforces the constraints.

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

### #17Alpheus  GDNet+

Posted 28 July 2012 - 01:45 PM

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)

I was just thinking this and was going to post it. But since you have already mentioned, I'll just reiterate by quoting you.

Edited by Alpha_ProgDes, 28 July 2012 - 01:50 PM.

External Articulation of Concepts Materializes Innate Knowledge of One's Craft and Science

Super Mario Bros clone tutorial written in XNA 4.0 [MonoGame, ANX, and MonoXNA] by Scott Haley

If you have found any of the posts helpful, please show your appreciation by clicking the up arrow on those posts

Spoiler

### #18Alpheus  GDNet+

Posted 28 July 2012 - 01:49 PM

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

But yours has more detail and a good point about C++.

Edited by Alpha_ProgDes, 28 July 2012 - 01:50 PM.

External Articulation of Concepts Materializes Innate Knowledge of One's Craft and Science

Super Mario Bros clone tutorial written in XNA 4.0 [MonoGame, ANX, and MonoXNA] by Scott Haley

If you have found any of the posts helpful, please show your appreciation by clicking the up arrow on those posts

Spoiler

Posted 28 July 2012 - 05:53 PM

If the variable needs bounds checking, validation, anything of those sorts - then yes.

### #20Akashi  Members

Posted 24 August 2012 - 02:52 PM

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.