If you have a simple ENUM with values only. Getters are available.
Any advise?
// ENUM with constructor and methods.
public enum Planet {
MERCURY(3.303e+23, 2.4397e6),
VENUS(4.869e+24, 6.0518e6),
EARTH(5.976e+24, 6.37814e6),
MARS(6.421e+23, 3.3972e6),
JUPITER(1.9e+27, 7.1492e7),
SATURN(5.688e+26, 6.0268e7),
URANUS(8.686e+25, 2.5559e7),
NEPTUNE(1.024e+26, 2.4746e7);
// Members
private final double mass; // in kilograms
private final double radius; // in meters
// Constructor
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
// Accessors
public double getMass() {
return mass;
}
public double getRadius() {
return radius;
}
}
Yes! also static methods. I'll show here an enum and two different tests.
Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.
Enum. IsDefined is a check used to determine whether the values exist in the enumeration before they are used in your code. This method returns a bool value, where a true indicates that the enumeration value is defined in this enumeration and false indicates that it is not. The Enum .
This is not a simple yes-or-no-question but depends very much on the context.
If this enum is a critical part of a huge project with a lot of programmers and weak communication structures and you want to assure that no one has accidentally changed this critical part, a reasonable junit test could look like this:
public class PlanetTest {
private final static int NUM_PLANETS = 8;
@Test
public void testIntegrity() {
assertEquals(NUM_PLANETS, Planet.values().length);
for (Planet planet : Planet.values()) {
assertTrue("Wierd: Mass in kg is less than radius in m",
planet.getMass() > planet.getRadius());
}
}
}
Writing this test case (with the help of an IDE) took even less time than reading your question and you are assured that no planet is missing or has corrupted values (once and for every regression test run).
Another benefit of writing test code (in test-driven development) is that the programmer is forced to think about implementation issues before he/she writes the actual code. This may improve the microdesign of code. Even in this trivial example I could think of issues to think about before implementing:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With