I’m doing some processing of images and in my work I use the package java.awt.geom. I am use the class Point. This class extends from Point2D and inherits get methods that return double. Point is meant to be an integer representation of a point.
To access the integer x and y values in Point you need to use publicly accessible variable x and y; My question is
1) Isn’t it bad practice to allow public access to an instance variable? eg. This question
2) Is there a better design of this?
Yes it is bad practice (at least by today’s standards), but there are a few reasons for this…
Point2Dneeds to be as generic as possibleIn detail…
Point2Dis a generic object used to represent any kind of point that can be represented in a 2D space. In order to have maximum use as a generic class, the point needs to allow for the highest level of precision possible (ie adouble). This is evident by thegetX()andgetY()methods that returndoubles. By usingdoubles, it allows any sub-class to be compatible with these methods, as a double is the largest primitive java number type with precision, so any sub-class that uses any other primitive numerical variable will always be able to return it as adoublewithout losing any precision.You can therefore think of
Pointas being a simplified version ofPoint2D, that doesn’t maintain any precision – however it must still conform to the abstract method declarations of the super-classPoint2D. Anintcan be cast into adoubledirectly by the JVM without losing any precision – ifPoint2Dwere something other than adouble, you would lose some of the precision during the cast. (For example, you couldn’t cast it to afloat, as largerintvalues wouldn’t be able to be directly represented as afloatwithout chopping off some of the higher numbers)File.separatorPointis a class that is used in a lot of places, and itself is still a pretty generic object. It is much easier/simpler/quicker for programmers to reference anintdirectly then it is to cast every time you want to get the value(int)getX(). It is also quicker to process by the JVM, as it doesn’t need to convert anintto adouble, and then back to anintagain.If you want a better design, you would probably be best to create additional methods for accessing the
intvalues asints – ie create the methodsgetXInt()andgetYInt(), and then change the variables back to being non-public (provided you don’t need to retain backwards compatibility).