Java Reference
In-Depth Information
client program be allowed to construct a TimeSpan object representing 0 hours and
157 minutes? A more natural representation of this amount would be 2 hours and 37
minutes. And what about values for hours or minutes that are negative? It doesn't
make sense to have a span of -2 hours or -35 minutes. Ideally we should not allow a
TimeSpan object to store such a value.
Let's make a design decision that we will only allow TimeSpan objects to store a
value for minutes that is between 0 and 59 inclusive. If the client tries to construct a
TimeSpan object with a negative number of hours or minutes, we could resolve the
problem by printing an error message or by setting the fields to 0. But in cases like
this, the negative value often comes from a bug or a mistake in the client's under-
standing of our class. The best way to handle a violation like this is to throw an
exception so that the client will know the parameter values passed were illegal.
If the user tries to construct a TimeSpan object with more than 60 minutes, we
will convert the excess minutes into hours. You might be tempted to use an if/else
statement or a loop to handle minutes above 60, but there is a simpler solution. For a
large number of minutes such as 157, dividing by 60 will produce the hours (2) and
using the % operator by 60 will produce the remaining minutes (37). The hours field
should really store the hours parameter plus the minutes parameter divided by 60,
and the minutes field should store the remaining minutes:
public TimeSpan(int hours, int minutes) {
if (hours < 0 || minutes < 0) {
throw new IllegalArgumentException();
}
this.hours = hours + minutes / 60;
this.minutes = minutes % 60;
}
A useful behavior of a TimeSpan object would be the ability to add more hours
and minutes to the span. An airline scheduling program might use this behavior to
add the elapsed times for two back-to-back flights to determine the total travel time
for a passenger's trip. Let's implement this behavior as a method called add that
accepts hours and minutes as parameters. Here's an initial incorrect version of that
method:
// an incorrect version of an add method
public void add(int hours, int minutes) {
this.hours += hours;
this.minutes += minutes;
}
The problem with the preceding code is that it allows the client to put the object
into an invalid state. If the client passes a value of minutes that is large enough to
make the total minutes greater than 60, the minutes field will have an invalid value.
Search WWH ::




Custom Search