Search code examples
javagetterconvention

Is it ok to get variable value directly instead of using getter in Java?


I'm writing program which operates on coordinate system so I need to use coordinates pretty often. I decided to use Point class because it obviously allows to easily store coordinates of a point.

The problem is everywhere in my program I store it as int whereas Point returns double when using getX() and getY() methods. Of course I can easily cast it to int but it doesn't look very elegant and adds unnecessary mess to the code.

Is it ok if I will just get the value directly? Like this:

Point p = new Point(0, 0);
int x = p.x;

instead of:

int x = p.getX();

I'm not even sure if it makes any difference, I just know that getters and setters are there for a reason and should be used.


Solution

  • I'm writing program which operates on coordinate system so I need to use coordinates pretty often. I decided to use Point class because it obviously allows to easily store coordinates of a point.

    and

    The problem is everywhere in my program I store it as int whereas Point returns double when using getX() and getY() methods.

    Are you sure that it obviously allows to easily store coordinates of a point for your domain?
    I don't think.
    Using the java.awt.Point classes makes sense if you need to manipulate some java.awt.Point instances.

    The class doesn't seem suit to your need.

    • If you really don't need to use java.awt.Point :

    You should create and use your own Point class that returns int value when you write :

    int x = p.getX();
    
    • If you change your mind and you happen to need to use java.awt.Point for some tasks:

    In the custom Point class, add a method to return a java.awt.Point instance.