• Create Account

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

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.

41 replies to this topic

### #1Wilfrost  Members

Posted 07 October 2012 - 08:28 PM

Hello all!

I've been lurking these forums for a while and finally decided to join up and be a real member of the community. I figured I'd introduce myself by asking everyone a simple question. When writing in an object oriented language, do you write a "getter" and "setter" method for every attribute of an object? What if you never intend to change the value of said attribute?

As an example: I'm working on my first game, a clone of pong. my class Ball has an attribute named size. Obviously the size of the ball in a game of pong never changes, but it felt strange to not write a setSize() method. Now I have code in my program that will never be used - and that feels a little strange too.

I know that there is no right or wrong answer to this question, I'm just interested in your individual opinions. Take it easy,

-Will

### #2MrDaaark  Members

Posted 07 October 2012 - 08:31 PM

If it doesn't vary, it's not a variable. It's a constant.

const float Size = whatever.whateverf; //<img src='http://public.gamedev.net//public/style_emoticons/<#EMO_DIR#>/smile.png' class='bbc_emoticon' alt=':)' />

### #3Wilfrost  Members

Posted 07 October 2012 - 08:43 PM

Good point!

Posted 07 October 2012 - 08:48 PM

Why write a function for something that's never going to change? While this may not occur much in the home-brew & hobby-est areas, I feel that you're adding the ability to mess with your game. You're just asking someone to abuse a function that was never meant to be used.

I have 10 fingers. That's not going to change. There is no standard function for me to remove a finger. If people are going to 'hack' away at me to attempt to remove said finger(s); I"m going to make them work [hard] for it.

Sorry if this reads weird - I have a bloody headache. :/

### #5slicksk8te  Members

Posted 07 October 2012 - 08:50 PM

"Getters" and "Setters" are an interface to the data contained in your class. It is typically good practice to do this when you allow data in the class to be accessed externally.
For instance if you had a variable in your Ball class named "speed", you may want to increase this as the game goes on longer. This would require a setter because the game needs to externally increase it. Then lets say you would like to check to see if the ball is off screen. This would require a getter for the position to figure out where the ball is.
Of course you could make the data public in the class but this is considered bad style and should be avoided except when absolutley necessary.

If it is only used in the class and never changed outside the class it should not have a getter or setter.

Hope this helps.

### #6Hodgman  Moderators

Posted 07 October 2012 - 08:53 PM

POPULAR

A well designed class should have very few "reasons to change". If you've got a class with 100 different functions that change it's state in different ways, then that's a sign that your class can probably be broken up into many smaller classes. See SRP.

If you do have a class that needs to have a lot of accessible/modifiable attributes, consider just using a struct with public data members and no functions.

Edited by Hodgman, 07 October 2012 - 08:54 PM.

### #7Bregma  Members

Posted 07 October 2012 - 09:09 PM

POPULAR

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.
Stephen M. Webb
Professional Free Software Developer

### #8Wilfrost  Members

Posted 07 October 2012 - 09:10 PM

Why write a function for something that's never going to change? While this may not occur much in the home-brew & hobby-est areas, I feel that you're adding the ability to mess with your game. You're just asking someone to abuse a function that was never meant to be used.

I guess I just have this little voice in the back of my head that says "Hey, you might want to have control over that some day... better write a set function for it"

Sorry if this reads weird - I have a bloody headache. :/

"Getters" and "Setters" are an interface to the data contained in your class. It is typically good practice to do this when you allow data in the class to be accessed externally.
For instance if you had a variable in your Ball class named "speed", you may want to increase this as the game goes on longer. This would require a setter because the game needs to externally increase it. Then lets say you would like to check to see if the ball is off screen. This would require a getter for the position to figure out where the ball is.
Of course you could make the data public in the class but this is considered bad style and should be avoided except when absolutley necessary.

If it is only used in the class and never changed outside the class it should not have a getter or setter.

Hope this helps.

I does! I appreciate everyone's opinion on the subject.

If you do have a class that needs to have a lot of accessible/modifiable attributes, consider just using a struct with public data members and no functions.

Are structs still around? I know that you can *technically* use them in C++ but I've never seen them called for in any C++ book I have, and tbh I have NEVER seen a struct used in Java - the language I have the most experience in (which is not saying much).

Thanks for all the great insights everyone, keep them coming!

### #9Wilfrost  Members

Posted 07 October 2012 - 09:15 PM

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.

### #10slicksk8te  Members

Posted 07 October 2012 - 09:21 PM

Structs are still alive and well, even in C++.
It just depends on what you are doing. In java there is no such thing as a struct. A class is the closest thing you have in java.

Structs are usually used for packing data at a lower cost than classes in most cases. This is why they are usually seen in lower level programming such as embedded systems In C++ the struct is deceptively similar to classes but there are some very important and distinct differences. Look here.

### #11Hodgman  Moderators

Posted 07 October 2012 - 09:26 PM

POPULAR

Are structs still around? I know that you can *technically* use them in C++ but I've never seen them called for in any C++ book I have, and tbh I have NEVER seen a struct used in Java

In C++ a struct and a class are exactly the same -- the only difference is that when using the struct keyword, the default access is 'public' and when using the class keyword the default keyword is 'private'.
For situations where you just need to pass around some data without enforcing invariants (which is what getters/setters are for), then using structs is fine.
They're often used to simplify function calls that require many arguments.
e.g.
public class BallParameters
{
public int size, mass, foo, bar, baz;
}
public class Ball
{
public Ball( BallParameters params ) { mass = params.mass; image = new Image("ball", size); }
private int mass;
private Sprite image;
}

### #12JiiPee  Members

Posted 08 October 2012 - 12:56 AM

I think you only need to hide the data from outside of the class, if the data must be handeled by some way in the class. Functions which shows outside of class are just an interface to manipulate the data properly. If you don't need to hide the data and secure the access to it, then you don't need one line getters and setters. I would prefer to show those variables outside of class. I.e. if you have a vector class, there is no reason to put x,y,z coordinate variables behind getters and setters. If you have some player class which increases it's x,y,z with some logic inside the class, then you might want to hide variables, so those variables are not modified with improper logic outside of class.

I think this logic is quite fine. I have read it from an algorithm book. Sorry but I can't remember the reference.
See my game dev blog: http://gamedev4hobby.blogspot.fi/

### #13i_luv_cplusplus  Members

Posted 08 October 2012 - 02:00 AM

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.

But wouldn't that break the SRP? You have a class that knows how to collide with walls and paddles, how to draw itself, what are it's physical properties. Isn't that too much?
OpenGL fanboy.

### #14Hodgman  Moderators

Posted 08 October 2012 - 02:33 AM

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.

But wouldn't that break the SRP? You have a class that knows how to collide with walls and paddles, how to draw itself, what are it's physical properties. Isn't that too much?

Not if the ball is composed out of a "physical ball" and a "drawable ball" member variable -- then the ball class's responsibility is to logically fuse those two members into a "gameplay ball".

### #15jefferytitan  Members

Posted 08 October 2012 - 03:09 AM

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.

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.

### #16EpicWally  Members

Posted 08 October 2012 - 01:05 PM

Take a look at chapter 6 in this book. The author does a pretty good job explaining the purpose of getters and setters, and objects vs data structures. Overall I think the other posters have hit the major points, but it's here as a reference. I've found this to be a very interesting read so far, and I would definitely recomend it.

### #17Xai  Members

Posted 08 October 2012 - 10:51 PM

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.

But wouldn't that break the SRP? You have a class that knows how to collide with walls and paddles, how to draw itself, what are it's physical properties. Isn't that too much?

Not if the ball is composed out of a "physical ball" and a "drawable ball" member variable -- then the ball class's responsibility is to logically fuse those two members into a "gameplay ball".

Programming, like all design and art and thought, has different techniques that feel natural to different people. There is no right way to play a guitar. There is no right way to do software development.

But my thought process is to have more interest in single responsibility and modeling and less in the original idea of "wholly controlled". I would not make a game object know how to draw itself and also do physics, I can't even imaging such a thing ... 2 totally independent concepts in my world ... and the physics or game engine deals with 1 of them, while the UI deals with the other.

### #18iMalc  Members

Posted 09 October 2012 - 12:11 AM

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

YAGNI!
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

Posted 09 October 2012 - 07:36 AM

I often write getters and setters. Not everytime I declare a variable, of course.

I think first we should not associate getters and setters so tightly.

A setter is potentially a lot more dangerous than a getter. On the other hand I assume it might be convenient to implement a getter, expecially if you are subclassing.

For this reason in my code a setter is often declared as protected.

While it is true a constant might be enough and I totally understand the point behind YAGNI for any non-trivial project I usually have data loaded from an external file. I want to be able to modify the datafile and restart, no recompilation needed.

In that case a public getter and a protected setter are a useful combination.

The point is if you are programming since years it is likely you have self-contained components which might be reused for different projects so it makes sense from my point of view to take a component I already have in my toolbox, create new classes according to my needs, tweak the data files and see what happens.

### #20DARSC0D3  Members

Posted 09 October 2012 - 08:28 AM

No you don't need to write setters and setter for every field in your class. Only if think you are going to use them or have the need for them to be public.
Making such decision is all up to you and is called software design. Use your logic to layout the classes in such way that they will work together but also will not cause problems behavior wise when you are able to modify properties publicly.

As for getters and setters them self. I have feel obligated to say they are not so great as every body might think. Actually they are even evil. First of all for the fact that most people never put anything in a getter setter block besideds passing true a value which is actually just mindless typing working which doesn't make sense at all.
Secondly for the fact that getters and setters are no more than syntax sugar in the end it is a function that return a fields value and set a value using function. With that said it more logical to make a function/method that has a better description about what the operation is going to preform on a class.

Compare the following example
[source lang="java"] spaceship = new SpaceShip(imgSpaceShip, posx, posy); if( spaceship.x < screen.width) spaceship.x += speed; if( spaceship.Y < screen.width) spaceship.y += speed;[/source]

to..

[source lang="java"] spaceship = new SpaceShip(imgSpaceShip,posx,posy,speed); spaceship.move(screen);[/source]

This is a small part pseudo code that reflects real good what I mean that using getters and setters does not promote better software design. It is not even considered OOP.
I used to be a big fan off getters and setters until I starting using more languages that had no syntax sugar for getters and setters. At first it hated it then i found out that I wrote better OOP and made less mistakes due better open close principle and that methods attached to classes where better descriptions on them self. If you would still feel the need for model / object to have mainly public properties you might think of using a struct. Therefor I have to disagree with people in this thread whom claim that structs and classes are the same this is simple not true.

Edited by DARSC0D3, 09 October 2012 - 08:29 AM.

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.