• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Wilfrost

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

41 posts in this topic

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
0

Share this post


Link to post
Share on other sites
Good point! [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
0

Share this post


Link to post
Share on other sites
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. :/
2

Share this post


Link to post
Share on other sites
"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.
2

Share this post


Link to post
Share on other sites
[quote name='ShadowValence' timestamp='1349664497' post='4987843']
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.
[/quote]

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"

[quote name='ShadowValence' timestamp='1349664497' post='4987843']
Sorry if this reads weird - I have a bloody headache. :/
[/quote]

Hope your head feels better!

[quote name='slicksk8te' timestamp='1349664612' post='4987844']
"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.
[/quote]

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

[quote name='Hodgman' timestamp='1349664839' post='4987845']
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.
[/quote]

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!
1

Share this post


Link to post
Share on other sites
[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.
[/quote]

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

Share this post


Link to post
Share on other sites
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 [url="http://stackoverflow.com/questions/2750270/c-c-struct-vs-class"]here[/url].
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
[quote name='i_luv_cplusplus' timestamp='1349683217' post='4987898']
[quote name='Bregma' timestamp='1349665762' post='4987846']
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.[/quote]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?[/quote]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".
2

Share this post


Link to post
Share on other sites
[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.
[/quote]

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

Share this post


Link to post
Share on other sites
Take a look at chapter 6 in [url="http://www.e-reading.org.ua/bookreader.php/134601/Clean_Code_-_A_Handbook_of_Agile_Software_Craftsmanship.pdf"]this book[/url]. 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.
0

Share this post


Link to post
Share on other sites
[quote name='Hodgman' timestamp='1349685222' post='4987905']
[quote name='i_luv_cplusplus' timestamp='1349683217' post='4987898']
[quote name='Bregma' timestamp='1349665762' post='4987846']
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.[/quote]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?[/quote]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".
[/quote]
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.
0

Share this post


Link to post
Share on other sites
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.

:)
0

Share this post


Link to post
Share on other sites
[quote name='DARSC0D3' timestamp='1349792937' post='4988364']
First I will answer your question.
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.
[/quote]

I agree totally with this idea. It is quite the same what I also said. It's much better design, if you put logic under a function inside the class rather than passing values in and out via getter and setter and do the logic outside of the class.

Also Baase and Van Gelder refers to this design in the "Computer Algorithms: Introduction to Design and Analysis" book.
0

Share this post


Link to post
Share on other sites
Another newbie here finding it hard to grasp these object oriented principles. I think I understand the core idea but extending it to practical applications leaves me confused everytime as to what data should be public or private, or where interfaces should be etc:

As an example, a platform game. When an actor moves it needs to find the actors and tiles nearby to collide with (stored in a World object say). When it collides it needs to know the exact position of the other actor, plus what kind of shape it is, and how the collision will be resolved (moving the shape back maybe). How should access to this information be handled? Where should the code that is calculating the collision be contained in and run from?

Sorry if these questions sound dumb but this stuff leaves me completely lost :/
0

Share this post


Link to post
Share on other sites
[quote name='zqf' timestamp='1349878892' post='4988728']
Another newbie here finding it hard to grasp these object oriented principles. I think I understand the core idea but extending it to practical applications leaves me confused everytime as to what data should be public or private, or where interfaces should be etc:

As an example, a platform game. When an actor moves it needs to find the actors and tiles nearby to collide with (stored in a World object say). When it collides it needs to know the exact position of the other actor, plus what kind of shape it is, and how the collision will be resolved (moving the shape back maybe). How should access to this information be handled? Where should the code that is calculating the collision be contained in and run from?

Sorry if these questions sound dumb but this stuff leaves me completely lost :/
[/quote]

First, the public vs. private argument. I'm fairly new to programming myself, but in general, from what I've read, I make everything private unless I'm given a compelling reason to do otherwise.

In your example, the "actor" would not need to find the other actors. In fact, it shouldn't really even know they exist. All this should be handled by some other physics engine, which handles all the actors, and calculates colisions. When a colision occurs, it calls the necessary method on the actor. i.e. changing movement speed/direction. The actor really only know where it is, and how to move. The physics engine gives it the specifics. Similarly the actor shouldn't know about keyboard inputs, gravity, or anything like that.
0

Share this post


Link to post
Share on other sites
What about the actor sending itself to some World interface to be moved during it's Update() (like World.MoveActor(this)) ?
0

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  
Followers 0