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!
#OOP question
14 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @glad kite! Please use
/closeor theClose Postbutton 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.
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
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
@vocal python I'm sorry, but what do you mean with you probably shouldn't want the setters?
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
yeah, i'm aware of the java record. I think my question is more about when we can break oo design, if we could
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