Jump to content

  • Log In with Google      Sign In   
  • 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.

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

#21 JiiPee   Members   -  Reputation: 135

Like
0Likes
Like

Posted 09 October 2012 - 08:41 AM

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.


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.
See my game dev blog: http://gamedev4hobby.blogspot.fi/

Sponsor:

#22 zqf   Members   -  Reputation: 374

Like
0Likes
Like

Posted 10 October 2012 - 08:21 AM

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 :/

#23 EpicWally   Members   -  Reputation: 282

Like
0Likes
Like

Posted 10 October 2012 - 09:43 AM

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 :/


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.

#24 Telastyn   Crossbones+   -  Reputation: 3730

Like
5Likes
Like

Posted 10 October 2012 - 10:17 AM

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.

#25 zqf   Members   -  Reputation: 374

Like
0Likes
Like

Posted 10 October 2012 - 10:27 AM

What about the actor sending itself to some World interface to be moved during it's Update() (like World.MoveActor(this)) ?

#26 Telastyn   Crossbones+   -  Reputation: 3730

Like
1Likes
Like

Posted 10 October 2012 - 11:32 AM

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

#27 Wilfrost   Members   -  Reputation: 142

Like
0Likes
Like

Posted 10 October 2012 - 01:57 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.


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.


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, 10 October 2012 - 02:14 PM.


#28 DARSC0D3   Members   -  Reputation: 379

Like
0Likes
Like

Posted 10 October 2012 - 02:06 PM

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.


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.


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 ;)

#29 Bacterius   Crossbones+   -  Reputation: 9282

Like
1Likes
Like

Posted 10 October 2012 - 02:34 PM


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.

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.

The slowsort algorithm is a perfect illustration of the multiply and surrender paradigm, which is perhaps the single most important paradigm in the development of reluctant algorithms. The basic multiply and surrender strategy consists in replacing the problem at hand by two or more subproblems, each slightly simpler than the original, and continue multiplying subproblems and subsubproblems recursively in this fashion as long as possible. At some point the subproblems will all become so simple that their solution can no longer be postponed, and we will have to surrender. Experience shows that, in most cases, by the time this point is reached the total work will be substantially higher than what could have been wasted by a more direct approach.

 

- Pessimal Algorithms and Simplexity Analysis


#30 zqf   Members   -  Reputation: 374

Like
0Likes
Like

Posted 10 October 2012 - 03:00 PM

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?

#31 Telastyn   Crossbones+   -  Reputation: 3730

Like
0Likes
Like

Posted 10 October 2012 - 03:24 PM

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?


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.

#32 zqf   Members   -  Reputation: 374

Like
0Likes
Like

Posted 10 October 2012 - 03:38 PM

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

#33 SIC Games   Members   -  Reputation: 617

Like
0Likes
Like

Posted 10 October 2012 - 10:20 PM

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. :)

Game Engine's WIP Videos - http://www.youtube.com/sicgames88


#34 TheChubu   Crossbones+   -  Reputation: 4766

Like
0Likes
Like

Posted 11 October 2012 - 12:12 AM

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, 11 October 2012 - 12:14 AM.

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

 

My journals: dustArtemis ECS framework and Making a Terrain Generator


#35 Bacterius   Crossbones+   -  Reputation: 9282

Like
1Likes
Like

Posted 11 October 2012 - 12:22 AM

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.

The slowsort algorithm is a perfect illustration of the multiply and surrender paradigm, which is perhaps the single most important paradigm in the development of reluctant algorithms. The basic multiply and surrender strategy consists in replacing the problem at hand by two or more subproblems, each slightly simpler than the original, and continue multiplying subproblems and subsubproblems recursively in this fashion as long as possible. At some point the subproblems will all become so simple that their solution can no longer be postponed, and we will have to surrender. Experience shows that, in most cases, by the time this point is reached the total work will be substantially higher than what could have been wasted by a more direct approach.

 

- Pessimal Algorithms and Simplexity Analysis


#36 DARSC0D3   Members   -  Reputation: 379

Like
0Likes
Like

Posted 11 October 2012 - 03:01 AM

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


Don't be afraid for that, most programmers still have habits on which could be improved on.
I takes years to perfect your art Posted Image. 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, 11 October 2012 - 03:21 AM.


#37 TheChubu   Crossbones+   -  Reputation: 4766

Like
0Likes
Like

Posted 11 October 2012 - 01:57 PM

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, 11 October 2012 - 02:14 PM.

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

 

My journals: dustArtemis ECS framework and Making a Terrain Generator


#38 TheChubu   Crossbones+   -  Reputation: 4766

Like
0Likes
Like

Posted 11 October 2012 - 02:04 PM

EDIT: Oops, double post.

Edited by TheChubu, 11 October 2012 - 02:15 PM.

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

 

My journals: dustArtemis ECS framework and Making a Terrain Generator


#39 Ravyne   GDNet+   -  Reputation: 8160

Like
2Likes
Like

Posted 11 October 2012 - 02:30 PM

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

#40 zqf   Members   -  Reputation: 374

Like
0Likes
Like

Posted 11 October 2012 - 02:38 PM

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, 11 October 2012 - 02:39 PM.





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