• Advertisement

# "Getters" and "Setters" - do you write them if you don't need them?

This topic is 1926 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

## Recommended Posts

IMO, an actor should not reference objects at a higher level than itself, including the world.

#### Share this post

##### Share on other sites
Advertisement

[quote name='Wilfrost' timestamp='1349666150' post='4987848']
[quote name='Bregma' timestamp='1349665762' post='4987846']
If you're writing software using object-oriented techniques, you rarely need getters and setters. Conversely, if you have a lot of getters and setters, you're not using object-oriented techniques, you're doing structured procedural programming. Don't fool yourself that because you use the 'class' keyword you're necessarily doing anything object-oriented.

An object-oriented ball doesn't ever need something else to tell it what its size is. Nothing else needs to know its size. It knows how to collide with walls and paddles. It knows how to draw itself.

I really like the way you stated that. I guess I have some thinking to do about the way my "objects" handle themselves.
[/quote]

Yes and no. I agree that other classes shouldn't be calculating using the ball size, e.g. doing collisions for the ball, etc. However no class is totally self contained. The ball needs to get it's size from somewhere, e.g. a constructor. Changing the size at runtime could be useful, e.g. power-ups that make it easier/harder by changing the ball size.
[/quote]

That is exactly how I was looking at it. I may want to implement a powerup where the ball get's bigger, smallet, whatever... And for that I would need to set the ball's size, so I would have to write a setSize() function. Along the same lines, my ball needs to know where the paddles are for collision detection, so my paddles need "get" functions for their xLocation, yLocation ,height, and width variables. The ball is still detecting for itself when the collision is happening, and it is reversing its own direction, but it has to get that information out of the paddle through four get functions.

As a side note: Some of my classes have attributes that are used only within the class and will never ever ever need to be influenced directly from outside. I do not write setters / getters for those.

I shall sum up my answer into one 5 letter acronym (google it):
YAGNI!

I did, and it makes perfect sense! Edited by Wilfrost

#### Share this post

##### Share on other sites

IMO, an actor should not reference objects at a higher level than itself, including the world.

I fully agree with you on this but still I would see this a design decision.

[quote name='zqf' timestamp='1349878892' post='4988728']
When an actor moves it needs to find the actors and tiles nearby to collide with (stored in a World object say).

That's why actors don't move themselves. Something moves them (and can then know enough to handle collision between actors).

Unfortunately, much of OOP turns out to be a bad idea. Not everything is an object. Objects shouldn't necessarily contain all of their state and behavior. These are traditional concepts that are unfortunately still taught heavily at universities.

The focus should be on the SOLID principles. These are more general principles that are great for OO as well as other paradigms. They've evolved over years of use (and academic study in some cases). Hope they help.
[/quote]

Yet again I agree with this too but this pore guy just got flooded with advanced practices. I tried to keep the answer with in context of his question ;)

#### Share this post

##### Share on other sites

[quote name='zqf' timestamp='1349878892' post='4988728']
When an actor moves it needs to find the actors and tiles nearby to collide with (stored in a World object say).

That's why actors don't move themselves. Something moves them (and can then know enough to handle collision between actors).

Unfortunately, much of OOP turns out to be a bad idea. Not everything is an object. Objects shouldn't necessarily contain all of their state and behavior. These are traditional concepts that are unfortunately still taught heavily at universities.

The focus should be on the SOLID principles. These are more general principles that are great for OO as well as other paradigms. They've evolved over years of use (and academic study in some cases). Hope they help.
[/quote]
This. A billion times. Naive OOP works fine some of the time, but as soon as you hit an edge case, things start breaking down, patterns fail and the next thing you know, you're using world callbacks in your entities.

#### Share this post

##### Share on other sites
How about the world holding a list of movers that it calls when it updates? Objects that want to move would add themselves to this list, that sort of thing?

#### Share this post

##### Share on other sites

How about the world holding a list of movers that it calls when it updates?

That's fine, but doesn't deal with collision. Something has to mediate movement with collision.

Objects that want to move would add themselves to this list, that sort of thing?
[/quote]

No. Something that knows about the list and the object can work between them.

And let's be clear here. I'm just offering advice. In the end, no software is perfect. In the end, if it runs correctly then the code is good enough. And all the forum chat in the world isn't going to make you a good program designer. Only practice will.

If you think something is a good idea, go try it out. If it causes you trouble, think of why and use that when you make the next game.

#### Share this post

##### Share on other sites
Thanks for your replies. I'm mainly just paranoid about getting into bad habits

#### Share this post

##### Share on other sites
If the variable are consantly changing then don't use getters and setters. In fact, the editor I am making uses less getters and setters that previous draft versions. But what is a setter and a getter - ask yourself? A setter is just a function that sets a variable. So, if you think of a player's position and some way you want to retrieve the player's position then you can have a set up like this:

 float3 PlayerPosition = x,y,z; float3 getPlayerPosition() { return PlayerPosition; } 

This is the approach I use but may vary with other users. So, for example say I set the player X: 5 units, Y: 0 units and Z: -15 unites as a starting point. If I want to run a conditional IF statement to see if the player has reached 0 units in the Z direction then making the code above works well. How?

 float PlayerZ = XMGetVectorZ(GetPlayerPosition); if(PlayerZ > 0) { ... Do whatever } 

So; you can see clearly that the Getter Function works well in this instance. The XMGetVectorZ extracts the Z position allowing the IF Condition Statement to see if the player is more than 0 on the Z Axis.

You can do the same as with a boolean or a integar.

 int score = 500; int getScore() { return score; } if(getScore() > 1000) { .. Do Level Up or whatever. } 

Hope this helps at least.

#### Share this post

##### Share on other sites
Can I hijack this thread a little?

Now, in uni we're being taught OOP, using Java. One thing that I didn't quite understand (and if I did, then I disagree) is making (protected) setters of the (private) attributes of a class for using them in the constructor of the same class.

What's going on there? Encapsulating the class from itself?

IMO looks useless and inefficient. The first thing that comes to mind when I think "What could have free access to this class's properties?" is the constructor. Why should need to use methods to access the class's attributes its trying to construct? It's one of those "It's in the paradigm!" things? Moreover, the classes that inherit from such class will also carry the "burden" of accessing itself through methods instead of simple direct attribute access.

I'd just use the getters and setters if I need to access the class's attributes from outside the class. It doesn't makes any sense to me to encapsulate the class from itself on constructors nor methods (except some "high risk" public method that could screw up the object that is, but probably that one should be implemented as a separate class anyway). Edited by TheChubu

#### Share this post

##### Share on other sites
Well, perhaps there is a particular variable that needs to be set in a very controlled manner, with a lot of side code to execute at each change, so they just take advantage of the getter/setter syntax to put all the code there instead of in a separate method. This is only useful if there *is* a getter/setter syntax (as in implicit call through assignment) which is not the case in Java, afaik - you only get the ugly getX(), getY(), etc...

It certainly depends on the context. Can you give an example of such a class?

Anyway, in general, the less methods your class has, the better it'll fare. I just hate seeing classes with fifty repetitive one-line getters and setters, it's so useless and redundant.

#### Share this post

##### Share on other sites

Thanks for your replies. I'm mainly just paranoid about getting into bad habits

Don't be afraid for that, most programmers still have habits on which could be improved on.
I takes years to perfect your art . Until then it might be a better idea to be productive than over think everything you doing.
By programming allot you will get a better picture about what type of relationships can be made between classes.

Everybody here might talk big about programming theorem but i bet you that we all still drop the ball every once in a while (that includes me).

If the variable are consantly changing then don't use getters and setters. In fact, the editor I am making uses less getters and setters that previous draft versions. But what is a setter and a getter - ask yourself? A setter is just a function that sets a variable. So, if you think of a player's position and some way you want to retrieve the player's position then you can have a set up like this:

You might consider reading the hole thread before posting a reply ;) Edited by DARSC0D3

#### Share this post

##### Share on other sites
It certainly depends on the context. Can you give an example of such a class?
Well, its exactly what you described. A bunch of one-line getters and setters for simple assignments dealing with ints, strings, and objects. Its getter/setter for everything.

Say:
public class blah { private int, x, y; private Object obj; public blah (int tmpX, int tmpY, Object tmpObj){ this.setX(tmpX); this.setY(tmpY); this.setObj(tmpObj);} protected setX (int tmpX){ this.x = tmpX} protected setY (int tmpY){ this.y = tmpY} protected setObj (Object tmpObj){ this.obj = tmpObj} } Edited by TheChubu

#### Share this post

##### Share on other sites
EDIT: Oops, double post. Edited by TheChubu

#### Share this post

##### Share on other sites
Getters and Setters aren't inherently wrong, but they're usually a code-smell (meaning: something smells fishy, there's probably an opportunity to improve this).

The idea of a class in OOP is that it encapsulates data together with methods that modify that data in ways which respect the internal rules of said class (for example, a ball class probably shouldn't have a negative radius). Getters themselves don't really violate this as long as they return by value or const reference, but they imply that other code might not be adhering to OO principles. Setters (especially simple one's that don't validate input or prevent an unexpected state from being reached) directly violate the class's ability to maintain its internal rules (e.g. a poorly-written SetRadius() function might allow a negative radius to be set, even if the constructor didn't).

In the case of the power-up example someone cited, rather than having the affected properties of the ball be directly modifiable by an outside entity, you might instead have a method on the Ball class which consumes a PowerUp instance and modifies its own state, or you might have a method on the PowerUp class that consumes a Ball instance, and returns a new Ball instance that represents the affect of the PowerUp on the old Ball instance.

Another point to be made is that when someone says "a ball knows how to draw itself" or somesuch, they don't typically mean that the ball class is making Direct3D or OpenGL calls itself, they usually mean something closer to "a ball provides an interface that can be used to draw it with minimal sharing of information."

#### Share this post

##### Share on other sites
I understand the desire to keeping game actors from seeing these large data structures, but I'm still trying to see what would be considered a safe way to bring them together? Is this where it is simplest to just make position and collision shape public variables or getters? Using movement and collision as an example still: The world loops through all actors, sends them to a collision class that can move the actor and call them when collisions occur? The collision class doesn't see all of the world, and can see the required details of the actor it's moving?

In this way objects don't control exactly how they are moved, or see any world information, they just have a velocity and a shape, and methods for responding to a collision. Edited by zqf

#### Share this post

##### Share on other sites

Can I hijack this thread a little?

Now, in uni we're being taught OOP, using Java. One thing that I didn't quite understand (and if I did, then I disagree) is making (protected) setters of the (private) attributes of a class for using them in the constructor of the same class.

What's going on there? Encapsulating the class from itself?

IMO looks useless and inefficient. The first thing that comes to mind when I think "What could have free access to this class's properties?" is the constructor. Why should need to use methods to access the class's attributes its trying to construct? It's one of those "It's in the paradigm!" things? Moreover, the classes that inherit from such class will also carry the "burden" of accessing itself through methods instead of simple direct attribute access.

I'd just use the getters and setters if I need to access the class's attributes from outside the class. It doesn't makes any sense to me to encapsulate the class from itself on constructors nor methods (except some "high risk" public method that could screw up the object that is, but probably that one should be implemented as a separate class anyway).

Let's review access levels:
Public: Everything can access this member function or member variable
Private: The member function/variable is only internally visible to the class
Protected: Publicly accessible by classes which inherit from this class, hidden from all other classes.

So, if you make the internal variables private and the accessors are protected, you're creating a layer of insulation between the internals of your class and any classes which want to inherit from it. This is handy for doing error checking to make sure that class data conforms to the class logic.

To OP:
Personally, I like accessor functions. I like to make a distinction between properties and methods in C#
 //These should NOT be "methods" because it's not really doing anything complicated to the data. It's just exposing the data to public use. public int GetX() { return m_x; } public void SetX(int value) { //arbitrary rule being enforced if(value >= 0) { m_x = value; } else { throw new exception("X shouldn't be negative!"); } } //instead, I like accessors which make it clear that you're accessing and using a property public int X { get{return m_x;} set { if(value >= 0) m_x = value; else throw new exception("blah blah"); } } 

Functionally, Get/Set methods are the same as accessors and can do some light error checking. But, I like to think of "functions" more as a set of instructions used to do operations on data. These sets of instructions are like a true, mathematical function and thus deserve the term "function" unlike simple get/set methods.
Example:
 public int Mandelbrot(float px, float py) { float x = 0; float y = 0; int iterations = 0; const int max_iterations = 100; while((x * x + y * y < 4) && iterations < max_iterations) { float tempx = x*x - y*y + px; y = 2*x*y + py; x = xtemp; iterations++; } return iterations; } 

The following advice may be frowned on or considered "bad", but its pragamatic:
If you're the only person working on a program, you can probably just let all of your class properties be public since you're the only one who will be using them. Nobody else is going to interfere with internal class data. I assume that you know what you're doing and how the class works internally when you're accessing variables which would otherwise be private. In general, the principle of "information hiding" is encapsulation in order to create a contract between the class creator and the class users. Since you're both creator and user, you probably don't need a contract with yourself (but you could treat your future self as a class user since you could forget implementation specifics).
If you're going to share your code, work with other people, or use it as a library, THEN it's a good idea to hide stuff you don't want people to access (to prevent other people from breaking your class). Generally, it's just a good habit to encapuslate data and expose it through methods and accessors (and to enforce validation on data that needs to be validated), but it can also be a waste of time if you're going solo. Use your best judgement.
Personally, I practice encapsulation and information hiding even on small personal projects. It's just a habit of discipline and helps manage where & how my classes are being accessed.

#### Share this post

##### Share on other sites
So, if you make the internal variables private and the accessors are protected, you're creating a layer of insulation between the internals of your class and any classes which want to inherit from it. This is handy for doing error checking to make sure that class data conforms to the class logic.
I've ended up using this kind of encapsulation and in that case I understand the idea behind getters, and setters in the constructors. I wouldn't want to have someone just extend some class and gain access to everything it has inside it right away potentially messing up the structure.

If you're going to share your code, work with other people, or use it as a library, THEN it's a good idea to hide stuff you don't want people to access (to prevent other people from breaking your class). Generally, it's just a good habit to encapuslate data and expose it through methods and accessors (and to enforce validation on data that needs to be validated), but it can also be a waste of time if you're going solo. Use your best judgement.
Yep, I agree with that. Though have in mind that I'm talking about getters and setters not as a whole but in the specific case of a constructor, It seems that it depends on what level of access you want to grant from the inherited classes (something I hadn't though about too much) and the kind of data validation you want to do in the methods (I prefer to validate the data before calling the constructor and/or methods of the object though).

Though for uni projects, getters and setters for everything in everything it seems!

#### Share this post

##### Share on other sites

• Advertisement
• Advertisement
• ### Popular Tags

• Advertisement
• ### Popular Now

• 10
• 11
• 9
• 12
• 10
• Advertisement