Search code examples
javareturn-valuepointreturn-typeimplicit-parameters

return object instance instead of function return in java (implicit parameter)


I would like to set a rectangle position relative to another component, but offsetted. I tried the following:

rndRect.setLocation(StartButt.getLocation().translate(buttW, 2));

but translate returns void, so it is not accepted as a parameter (requires a Point).

Is there a way to do it on the same statement without creating an auxiliary variable?

Nothing crucial, just curiosity.


Solution

  • No. If translate takes a mutable variable which is changed and not returned then you will need to declare a variable to pass to translate and then subsequently pass it to setLocation.

    Alternatively you could write your own method that takes a location and creates and returns a point:

    private Point translate(Location location, Point origin, int distance) {
        Point result = (Point)origin.clone();
        location.translate(result, distance);
        return result;
    }
    
    rndRect.setLocation(translate(StartButt.getLocation(), buttW, 2));
    

    As a matter of interest, opinions vary (a lot) over whether it's a good idea to have interim variables to hold values temporarily or, alternatively, to create fewer more complex statements that avoid interim variables. Personally I find well named interim variables (and short simple methods) make reading code much easier as you have less to hold in your head as you read each statement. The code tends to reads more like a story and less like a puzzle. In my experience, as coders get better through their careers they create more and simpler classes, methods, statement and variables to solve each problem.