Lets say I need to compare the x position of a ball with the x position of a rectangle to see if they have collided. Wouldn't it be easier to just declare x in ball as public so I can use ball.x instead of ball.getX()?

Recommended Answers

All 4 Replies

How on earth is that any easier? Because you type a few less characters??

How on earth is that any easier? Because you type a few less characters??

First of all, wouldn't that simple reason make it easier xD?
Second: This avoids having to write the get and set methods.
Third: It saves CPU resources, calling getX takes more CPU power than .x

So, what do you think xD?

Member Avatar for embooglement

The amount of CPU power it takes to call and return a simplistic get function is almost completely negligible. That said, traditional object-oriented programming usually involves hiding all data members, and accessing them purely through get/set functions. I always thought that "rule" was kind of silly though. There are definitely cases where having get/set functions is cumbersome and unnecessary, however those cases are relatively few.

The first problem is whether or not the entire range of the data type is valid for your class. For instance, when doing RGB colors using floats, the red, green, and blue are represented by a value between 0.0f and 1.0f. Having those be public would mean someone could do "someColor.red = 2.0f", which is nonsensical given the context, and therefore they should be private. However, if you were talking about something's position, "someBall.x = 2.0f" could very well be valid. The second thing is whether that data ought to be mutable by outside functions. If the thing a ball is colliding with can't alter the ball's position, then you shouldn't have them public. And finally, if other functions need to be called to determine how to get or set the value. An example might be a circle class that has it's radius and circumference as members. Whenever one value is changed, the other must be changed as well.

So, in my opinion, public data is permissible if the full range of the data type is valid for the class, the object's data can be changed by anything outside the class, and the changes that happen don't need any extra filtering. That's just my opinion though, and I'm sure others would disagree.

@OP: Your looking at it the wrong way, instead of letting the client check if a circle is intersects a rectangle, have the rectangle have a function called contains(Circle c) and call it like so, rectangleObject.contains(circleObject);

So that way there is more encapsulation, and a better design. Of course you would probably have to have getX() and getY() eventually, so might as well have a getX() and getY().

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.