Jump to content

  • Log In with Google      Sign In   
  • Create Account

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.

  • You cannot reply to this topic
19 replies to this topic

#1 Akashi   Members   -  Reputation: 268

Like
1Likes
Like

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.


Sponsor:

#2 ApochPiQ   Moderators   -  Reputation: 15765

Like
7Likes
Like

Posted 27 July 2012 - 10:51 AM

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.

#3 Akashi   Members   -  Reputation: 268

Like
1Likes
Like

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.


#4 MichaBen   Members   -  Reputation: 481

Like
9Likes
Like

Posted 27 July 2012 - 11:15 AM

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.

#5 Akashi   Members   -  Reputation: 268

Like
0Likes
Like

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.


#6 Ravyne   GDNet+   -  Reputation: 7409

Like
4Likes
Like

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.

#7 Akashi   Members   -  Reputation: 268

Like
0Likes
Like

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?

#8 nobodynews   Crossbones+   -  Reputation: 1917

Like
0Likes
Like

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!


#9 ApochPiQ   Moderators   -  Reputation: 15765

Like
7Likes
Like

Posted 27 July 2012 - 12:12 PM

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.

#10 Narf the Mouse   Members   -  Reputation: 318

Like
0Likes
Like

Posted 27 July 2012 - 12:59 PM

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

#11 omercan   Members   -  Reputation: 370

Like
0Likes
Like

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. Posted Image I do not.
Reading, Reading, Reading... why do you read not more?
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

#12 Alpha_ProgDes   Crossbones+   -  Reputation: 4688

Like
0Likes
Like

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 :P
Beginner in Game Development? Read here.
 
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 Posted Image
 
Spoiler

#13 Alpha_ProgDes   Crossbones+   -  Reputation: 4688

Like
5Likes
Like

Posted 27 July 2012 - 03:21 PM

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.

Beginner in Game Development? Read here.
 
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 Posted Image
 
Spoiler

#14 Akashi   Members   -  Reputation: 268

Like
0Likes
Like

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.

#15 SimonForsman   Crossbones+   -  Reputation: 6111

Like
1Likes
Like

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!

#16 darookie   Members   -  Reputation: 1437

Like
5Likes
Like

Posted 28 July 2012 - 04:47 AM

In addition to what was already said, my very concise answer to your question would be: No.
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 Posted Image

#17 Alpha_ProgDes   Crossbones+   -  Reputation: 4688

Like
0Likes
Like

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. Posted Image

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

Beginner in Game Development? Read here.
 
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 Posted Image
 
Spoiler

#18 Alpha_ProgDes   Crossbones+   -  Reputation: 4688

Like
0Likes
Like

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.

Beginner in Game Development? Read here.
 
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 Posted Image
 
Spoiler

#19 dimitri.adamou   Members   -  Reputation: 329

Like
0Likes
Like

Posted 28 July 2012 - 05:53 PM

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

#20 Akashi   Members   -  Reputation: 268

Like
0Likes
Like

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.
Thanks for your help.




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.



PARTNERS