Should I access int directly or get a double from the receiver and drop it?

As described in Why does java.awt.Point provide methods for setting and getting doubles, but store x and y as an int? The java.awt.Point Java class does not have a get method that returns an int . However, you can directly access x and y , which are int types.

With that said, which is the lesser of 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 adhere to the standard practice of using getters (access methods) whenever possible, but this scenario requires a throw. I can avoid the cast, but I have to access the x and y fields directly. Assuming internally that getX and getY just getY int into double , and then I return it back to int , it feels wrong.

+4
source share
1 answer

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

+4
source

Source: https://habr.com/ru/post/1400052/


All Articles