How do i condense these return statements or avoid the checkstyle error all together?

Matt :

Currently, I'm working on writing classes for a brick breaker game for my java class. I have a question about a checkstyle error I'm getting for my public javafx.scene.paint.Color getColor() method which gets the color of the brick based on how many times it has been hit by the ball.

The checkstyle error says: Return count is 6 (max allowed for non-void methods/lambdas is 2). which I assume it means I can only have 2 return statements as opposed to the 6 that I have currently. All of the statements have different returns based on the value of this.hits which is what I don't understand. The documentation for it is as follows:

public javafx.scene.paint.Color getColor()

The current color to represent this Brick's breakability state.
Returns:There are five possible Colors that can be returned based on 
theBrick's current strength: Color.BLACK if this Brick cannot be 
broken;Color.WHITE if this Brick has been completely broken; and 
Color.RED, Color.YELLOW,Color.GREEN if this Brick will break after 1, 2, 
and 3 more hits, consecutively.

And the code:

public javafx.scene.paint.Color getColor() {

        if (this.hits == -1) {
            return javafx.scene.paint.Color.BLACK;

        } else if (this.hits == 0) {
            return javafx.scene.paint.Color.TRANSPARENT;

        } else if (this.hits == 1) {
            return javafx.scene.paint.Color.RED;

        } else if (this.hits == 2) {
            return javafx.scene.paint.Color.YELLOW;

        } else if (this.hits == 3) {
            return javafx.scene.paint.Color.GREEN;
        }

        return null;
}
c0der :

The following method does the same with one return statement:

    public javafx.scene.paint.Color getColor() {

        javafx.scene.paint.Color color = null;

        if (this.hits == -1) {
            color = javafx.scene.paint.Color.BLACK;

        } else if (this.hits == 0) {
            color = javafx.scene.paint.Color.TRANSPARENT;

        } else if (this.hits == 1) {
            color = javafx.scene.paint.Color.RED;

        } else if (this.hits == 2) {
            color = javafx.scene.paint.Color.YELLOW;

        } else if (this.hits == 3) {
           color = javafx.scene.paint.Color.GREEN;
        }

        return color;
 }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=140005&siteId=1