...
This program implements the classic game of rock-paper-scissors, using the compareTo()
operator to determine the winner of a game.
Code Block | ||
---|---|---|
| ||
class GameEntry implements Comparable {
public enum Roshambo {ROCK, PAPER, SCISSORS}
private Roshambo value;
public GameEntry(Roshambo value) {
this.value = value;
}
public int compareTo(Object that) {
if (!(that instanceof Roshambo)) {
throw new ClassCastException();
}
GameEntry t = (GameEntry) that;
return (value == t.value) ? 0
: (value == Roshambo.ROCK && t.value == Roshambo.PAPER) ? -1
: (value == Roshambo.PAPER && t.value == Roshambo.SCISSORS) ? -1
: (value == Roshambo.SCISSORS && t.value == Roshambo.ROCK) ? -1
: 1;
}
}
|
...
This compliant solution implements the same game without using the Comparable
interface.
Code Block | ||
---|---|---|
| ||
class GameEntry {
public enum Roshambo {ROCK, PAPER, SCISSORS}
private Roshambo value;
public GameEntry(Roshambo value) {
this.value = value;
}
public int beats(Object that) {
if (!(that instanceof Roshambo)) {
throw new ClassCastException();
}
GameEntry t = (GameEntry) that;
return (value == t.value) ? 0
: (value == Roshambo.ROCK && t.value == Roshambo.PAPER) ? -1
: (value == Roshambo.PAPER && t.value == Roshambo.SCISSORS) ? -1
: (value == Roshambo.SCISSORS && t.value == Roshambo.ROCK) ? -1
: 1;
}
}
|
...
Automated detections of violations of this rule is infeasible in the general case.
Tool | Version | Checker | Description |
---|---|---|---|
Coverity | 7.5 | FB.RU_INVOKE_RUN | Implemented |
Related Guidelines
CWE-573. Improper following of specification by caller |
...