• 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

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

Share this post


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

[quote name='iMalc' timestamp='1349763089' post='4988232']
I shall sum up my answer into one 5 letter acronym (google it):
YAGNI!
[/quote]

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

Share this post


Link to post
Share on other sites
[quote name='Telastyn' timestamp='1349890357' post='4988781']
IMO, an actor should not reference objects at a higher level than itself, including the world.
[/quote]

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

[quote name='Telastyn' timestamp='1349885837' post='4988763']
[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).
[/quote]

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 [b]everything [/b]is an object. Objects shouldn't necessarily contain [i]all[/i] of their state and behavior. These are traditional concepts that are unfortunately still taught heavily at universities.

The focus should be on the [url="http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)"]SOLID[/url] 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 ;)
0

Share this post


Link to post
Share on other sites
[quote name='Telastyn' timestamp='1349885837' post='4988763']
[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).
[/quote]
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 [b]everything [/b]is an object. Objects shouldn't necessarily contain [i]all[/i] of their state and behavior. These are traditional concepts that are unfortunately still taught heavily at universities.

The focus should be on the [url="http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)"]SOLID[/url] 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.
1

Share this post


Link to 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?
0

Share this post


Link to post
Share on other sites
[quote name='zqf' timestamp='1349902844' post='4988856']
How about the world holding a list of movers that it calls when it updates?
[/quote]

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

[quote]
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.
0

Share this post


Link to post
Share on other sites
Thanks for your replies. I'm mainly just paranoid about getting into bad habits :)
0

Share this post


Link to 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:

[code]
float3 PlayerPosition = x,y,z;

float3 getPlayerPosition() {
return PlayerPosition;

}
[/code]

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?

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

[/code]

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.

[code]
int score = 500;
int getScore() {
return score;
}

if(getScore() > 1000) {
.. Do Level Up or whatever.
}

[/code]

Hope this helps at least. :)
0

Share this post


Link to 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 [b]outside [/b]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
0

Share this post


Link to 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.
1

Share this post


Link to post
Share on other sites
[quote name='zqf' timestamp='1349905105' post='4988874']
Thanks for your replies. I'm mainly just paranoid about getting into bad habits [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
[/quote]

Don't be afraid for that, most programmers still have habits on which could be improved on.
I takes years to perfect your art [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]. 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).

[quote name='SIC Games' timestamp='1349929258' post='4988952']
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:

[/quote]

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

Share this post


Link to post
Share on other sites
[quote name='Bacterius' timestamp='1349936563' post='4988979']It certainly depends on the context. Can you give an example of such a class?
[/quote]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:
[code]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}
}[/code] Edited by TheChubu
0

Share this post


Link to 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."
2

Share this post


Link to 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
0

Share this post


Link to post
Share on other sites
[quote name='TheChubu' timestamp='1349935966' post='4988978']
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 [b]outside [/b]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).
[/quote]

Let's review access levels:
[b]Public:[/b] Everything can access this member function or member variable
[b]Private: [/b]The member function/variable is only internally visible to the class
[b]Protected: [/b]Publicly accessible by classes which [i]inherit [/i]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#
[code]
//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");
}
}
[/code]

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:
[code]
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;
}
[/code]

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 [i]probably [/i]don't need a contract with yourself (but you could treat your [i]future[/i] 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.
1

Share this post


Link to post
Share on other sites
[quote name='slayemin' timestamp='1350033915' post='4989404']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.[/quote]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. [quote name='slayemin' timestamp='1350033915' post='4989404']
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.[/quote]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! :P
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