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?
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).
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.
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.
精彩评论