#OOP question

14 messages · Page 1 of 1 (latest)

glad kite
#

Hey guys! This is my first time posting here.
My question is about object oriented design. Let's say I have a really simple Position class which only contains two int variables x and y that represent the position of some other class, e.g. a vehicle. Following OOP principles this Position class should has their attributes encapsulated(private) and provide a set a methods to interact with them. But is it really worth in this case? I mean, it will have just getters, setters and a constructor and none other special behaviour. Wouldn't be more simple just make the variables public?
Thank you!

unreal treeBOT
#

This post has been reserved for your question.

Hey @glad kite! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

vocal python
#

If you want simple, it could be just a record rather than a class. Unless you do mean you want the setters, which you probably shouldn't

vivid ether
#

apis are generally based on methods, so you should aim for public methods as the api. fields don't work for this
methods also have the benefit of allowing method references, such as pointList.stream().map(Point::getX).toList();

#

as kyochan mentioned, records are a shortcut for making the getters and private fields

glad kite
#

@vocal python I'm sorry, but what do you mean with you probably shouldn't want the setters?

vocal python
#

It's better to keep your types immutable

#

Once the fields x and y are set, they can't be changed in this Position object. If you want a different positioning, you need a new Position object

glad kite
#

yeah, i'm aware of the java record. I think my question is more about when we can break oo design, if we could

vocal python
#

At the end of the day you're the programmer, you do what you want. Experience will show you that the way everything is expected in Java, it's not worth it to avoid methods

#

Also, I assume that positions may be negative, otherwise the obvious point of denying direct access to the variables, is to prevent setting invalid values

glad kite
#

right. I understand

#

thank you for your time :3