4

As described in Why does java.awt.Point provide methods to set and get doubles but store x and y as int's? the Java class java.awt.Point does not have a get method that returns an int. However, you can access x and y directly, which are both int types.

With that said, which is the lesser of the 2 evils?

Point location = this.getLocation();
int locX = (int)location.getX();
int locY = (int)location.getY();

or

Point location = this.getLocation();
int locX = location.x;
int locY = location.y;

I try to keep the standard practice of using getters (accessor methods) when possible, but in this scenario it requires a cast. I can avoid the cast, but I must access the fields x and y directly. Assuming that internally getX and getY are simply casting the int to a double and then I'm casting it back to an int, it feels wrong.

Community
  • 1
  • 1
Luke
  • 3,742
  • 4
  • 31
  • 50
  • The direct access approach is an example of bad design because it exposes the internals of the implementation. However, it is convenient for saving method calls, which can became significant for example in a loop. This optimization is common practice in videogame programming. I think the last option is the most natural. – Mister Smith Mar 06 '12 at 17:28

1 Answers1

4

The direct access method is slightly more efficient and looks nicer. It is technically bad practice to avoid the get/set methods if they exist, but in this case I think you should make an exception.

arc
  • 584
  • 2
  • 5