Search code examples
javaswingfinal

How do final local variables 'avoid repeat invocations' of methods?


Creating a GUI with JFC/Swing > Perform Custom Painting : Refining the Design

I was reading through the tutorial linked above and a portion of the example code has me perplexed. According to the code comment in the moveSquare method, storing location information as final local variables will

'avoid repeat invocations of the same methods'

This makes absolutely no sense to me and I was hoping that someone could expound on the meaning of the comment. (see link above for full source and tutorial commentary)

class MyPanel extends JPanel {

RedSquare redSquare = new RedSquare();

public MyPanel() {

    setBorder(BorderFactory.createLineBorder(Color.black));

    addMouseListener(new MouseAdapter(){
        public void mousePressed(MouseEvent e){
            moveSquare(e.getX(),e.getY());
        }
    });

    addMouseMotionListener(new MouseAdapter(){
        public void mouseDragged(MouseEvent e){
            moveSquare(e.getX(),e.getY());
        }
    });

}

private void moveSquare(int x, int y){

    // Current square state, stored as final variables 
    // to avoid repeat invocations of the same methods.
    final int CURR_X = redSquare.getX();
    final int CURR_Y = redSquare.getY();
    final int CURR_W = redSquare.getWidth();
    final int CURR_H = redSquare.getHeight();
    final int OFFSET = 1;

    if ((CURR_X!=x) || (CURR_Y!=y)) {

        // The square is moving, repaint background 
        // over the old square location. 
        repaint(CURR_X,CURR_Y,CURR_W+OFFSET,CURR_H+OFFSET);

        // Update coordinates.
        redSquare.setX(x);
        redSquare.setY(y);

        // Repaint the square at the new location.
        repaint(redSquare.getX(), redSquare.getY(), 
                redSquare.getWidth()+OFFSET, 
                redSquare.getHeight()+OFFSET);
    }
}

public Dimension getPreferredSize() {
    return new Dimension(250,200);
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);       
    g.drawString("This is my custom Panel!",10,20);

    redSquare.paintSquare(g);
}  
}

Solution

  • This means that the result from calling getX() or the other methods is saved in a variable and reused so that you don't have to keep calling those methods every time you need the X or Y.

    This has three advantages:

    1. The code is more readable due to the variable names
    2. Performance is improved due to the methods not having to be called again and again
    3. Future changes are possibly easier because you only have to change method names in one place for example.