This question is not Java specific, however the code examples are in Java.
Sometimes you encounter very simple objects, like the following code:
public class Coordinates {
private int x;
private int y;
public Coordinates (int x, int y) {
this.x = x;
this.y = y;
}
public void setX (int x) { this.x = x; }
public void setY (int y) { this.y = y; }
public int getX () { return x; }
public int getY () { return y; }
}
I would say it would be much more efficient to access fields directly rather than through methods. Plus, the code would look simpler. The use itself would be simpler, and the class definition would be free of (unnecessary boiler-plate code) 4 methods than don't really do anything. (In a way I'm thinking of a use similar to struct
in C or record
in Pascal.)
The way I would do it is probably like this:
public class Coordinates {
public int x;
public int y;
public Coordinates (int x, int y) {
this.x = x;
this.y = y;
}
}
So why does the first way seem preferred? It feels like forcing something into becoming an object. It is just values bunched together into one variable, why using OOP just for the sake of it? True, I have kept the constructor. It is actually handy for when values are initially assigned, but there really is no need for other methods, except maybe a method set
that sets both fields (like the constructor).
I know OOP is handy for many things, but to me this doesn't seem to be one of them. Am I wrong thinking like that?