sova
sova

Reputation: 5658

Conditional check and return without variable, calling method twice: Possible?

Upon pre-submission review, I realize this question might be incredibly silly.

if (this.gameOver(gpos) > 0) {
    //do stuff
    return this.gameOver(gpos);
}

Compare

if (this.gameOver()) {
    //do stuff
    return this.gameOver(gpos);
}

I was in doubt as to whether or not the first example would call this.gameOver(gpos); twice or just once at the beginning. Obviously, it does call it twice (right?), but is there any way (without an intermediate variable) to have it check the condition AND be in the return statement at the same time?

Upvotes: 0

Views: 686

Answers (3)

hisdrewness
hisdrewness

Reputation: 7651

I believe the observer pattern would work well here.

Essentially, you would have something like a observer Console Class (think xbox console, etc.), which is an observer of any observable Game class. When the game is completed, it could fire an event to notify the Console that the Game is complete, beaten, paused, etc.

Many GUI frameworks like GWT, RCP, etc. can make use of observer to publish events between windows/views.

Upvotes: 0

Brandon DuRette
Brandon DuRette

Reputation: 4870

The first implementation will call this.gameOver(gpos) twice. I don't know of a clean way to conditionally return that value without storing in a temporary. Is there some reason that you cannot use a temporary variable here? There are some hackish solutions that make the code less readable (and probably slower).

Upvotes: 1

Ben Taitelbaum
Ben Taitelbaum

Reputation: 7403

While I believe this is bad design, I do believe it allows for what you want:

boolean gameOver(GamePosition gp) {
   // example
   if (this.gameOver)
     return true;
   else
     throw new Exception();
}

void someMethod() {
  try {
    return gameOver(gp);
  } catch (Exception e) {
    // other logic for when the game is not over
  }
}

Now, a better design would be to just have a method isGameOver(gp), and as you mentioned, store that to a local variable.

Upvotes: 0

Related Questions