Referencing an object more than once in a line

So I'm writing my version of Tetris. Here's what I'd like to do:

screen[0][1].setColor(Color.RED); screen[0][1].setStatus(1);

Is there a way to do this in only one line?

Jon Skeet
people
quotationmark

A few options spring to mind:

  • Write a method in whatever class this is which knows about both the status and the color:

    // Implicitly sets color to red. Consider using an enum for statuses
    screen[0][1].setStatus(1); 
    
  • Write a method accepting both state and color parameters:

    screen[0][1].setColorAndStatus(Color.RED, 1);
    
  • Make setColor and setStatus (and other setters) return this so you can chain them:

    screen[0][1].setColor(Color.RED).setStatus(1);
    
  • Abandon the "all in one statement" idea (which is what I think you really meant - you can put two statements on one line if you really want, but I'm not suggesting that you do) and actually write three statements:

    Tile tile = screen[0][1];
    tile.setColor(Color.RED);
    tile.setStatus(1);
    

people

See more on this question at Stackoverflow