HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Critique of enum

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
enumcritiquestackoverflow

Problem

I'm working my way through The Java Programming Language, Fourth Edition - The Java Series. This is Exercise 6.4:


Expand your traffic light color enum from Exercise 6.1 on page 152 so that each enum constant has a suitable Color object that can be retrieved with getColor.

The enum from Exercise 6.1 is as follows:

enum TrafficLightColor {
    GREEN,
    RED,
    YELLOW,
}


Is the following an adequate solution?

enum TrafficLightColor {
    GREEN(0, 255, 0),
    YELLOW(255, 255, 0),
    RED(255, 0, 0);

    Color color;

    TrafficLightColor (int r, int g, int b) {
        color = new Color(r, g, b);
    }

    Color getColor() {
        return color;
    }
}

public class Color {
    private int r;
    private int g;
    private int b;

    Color(int r, int g, int b) {
        this.r = r;
        this.g = g;
        this.b = b;
    }

    public int getR() {
        return r;
    }

    public int getG() {
        return g;
    }

    public int getB() {
        return b;
    }
}

public class TrafficLight {
    private TrafficLightColor currentColor;

    TrafficLight(TrafficLightColor currentColor) {
        this.currentColor = currentColor;
    }

    TrafficLightColor getCurrentColor() {
        return currentColor;
    }
}

import org.junit.Test;
import static org.junit.Assert.*;

public class TrafficLightTest {
    @Test
    public void testGetCurrentColor() throws Exception {
        TrafficLight light = new TrafficLight(TrafficLightColor.GREEN);
        assertEquals(0, light.getCurrentColor().getColor().getR());
        assertEquals(255, light.getCurrentColor().getColor().getG());
        assertEquals(0, light.getCurrentColor().getColor().getB());

    }
}

Solution

Certainly, that seems adequate. You may want to make the color field private, though. Otherwise having a getter is pretty irrelevant. Also, I would make the field final so that the associated color can never be modified.

Were you told to code your own Color class? There's already one provided for you in java.awt.

Context

StackExchange Code Review Q#31958, answer score: 3

Revisions (0)

No revisions yet.