Class variables question

I'm writing a simple pong game and have a ball, paddle, and board class. In the past I've always pretty much kept my class members/variables as I've heard that's the proper way to do so. However now I'm realizing now that I am using more OOP designs that when I want to check for collision in my game looop I'll need to check the ball.x and paddle.x, and y against each other. I cannot do that check if those vairables are private in their own class.

How do you suggest I go about this?
You can always create a public get() method.
I suppose so, is that the popular way of doings things in my case/scenario?
closed account (1v5E3TCk)
Creating getter and setter methods is proper way to get private variable values from an object and set new values to them.
Does that not kind of defeat the purpose of data encapsulation though? I guess if there is only one means of accessing the data then it's still safe, but seems to defeat that purpose.
No, because you make sure you only create public getters and setters where appropriate for the interface. You don't blindly write them for every data member, but you write them where they're essential for the class to provide the services that it needs to.

Also, you may want to change the implementation of your class at some point, such that it no longer has simple x and y data members. If you were simply making those data members public, that would break all the code that accesses them, and you'd have to change the code everywhere that happens. By having interface methods, all you'd need to do is change the way those methods are implemented. The rest of the code can carry on calling getX() and getY() (or whatever), without being impacted by the fact that, under the hood, the class has changed the way it works.
Topic archived. No new replies allowed.