1

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?

  • You could make a method combing the two into one for all future calls. – Wold Apr 12 '14 at 06:16
  • 3
    rewrite the `setColor` and/or `setStatus` methods to return `this`. Then it's `screen[0][1].setColor(Color.RED).setStatus(1)`. The real question is: why would you need to? I severely doubt you're running into performance issues over these two lines, keep them nice and readable =) – Mike 'Pomax' Kamermans Apr 12 '14 at 06:17
  • Whoa @Mike'Pomax'Kamermans that's pretty clever. I guess it really doesn't accomplish anything though. – Mdev Apr 12 '14 at 06:22

4 Answers4

3

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);
    
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Just for the same of accomplishing this, you could change methods setColor() and setStatus() to return this. Something like:

public MyObj setColor(int color) {
    this.color = color;
    return this;
}

But I wouldn't do this, it doesn't seem like a good pattern, unless other methods follow the same approach.

Daniel Gabriel
  • 3,939
  • 2
  • 26
  • 37
0

Direct possibilities.

  • Yes

if setColor method returning the object of type screen[0][1] then you can do

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

if setColor method return type is void. Then only way is

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

If you are able to edit the class , there are many other ways we have here so far :)

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

The possible method can be anyone given by others :

also try it

(screen[0][1].setColor(Color.RED)).setStatus(1);
Raju Sharma
  • 2,496
  • 3
  • 23
  • 41