Java Reference
In-Depth Information
Properties props = new Properties();
props.setProperty("a", "5");
props.setProperty("b", "true");
props.setProperty("c", "-3");
Now let's also suppose your program needs to read a value from these Properties that it will
interpret as a duration in seconds. Because a duration has to be a positive number, you'll want a
method with the following signature
public int readDuration(Properties props, String name)
that, when the value of a given property is a String representing a positive integer, returns that
integer, but returns zero in all other cases. To clarify this requirement you can formalize it with a
few JUnit assertions:
assertEquals(5, readDuration(param, "a"));
assertEquals(0, readDuration(param, "b"));
assertEquals(0, readDuration(param, "c"));
assertEquals(0, readDuration(param, "d"));
These assertions reflect the original requirement: the readDuration method returns 5 for the
property "a" because the value of this property is a String that's convertible in a positive number;
it returns 0 for "b" because it isn't a number, returns 0 for "c" because it's a number but it's
negative, and returns 0 for "d" because a property with that name doesn't exist. Let's try to
implement the method satisfying this requirement in imperative style, as shown in the following
listing.
Listing 10.7. Reading duration from a property imperatively
 
Search WWH ::




Custom Search