22
33class TempStats
44{
5+ private const double LOWEST_TEMPERATURE = - 128.6 ;
6+
7+ // https://en.wikipedia.org/wiki/Lowest_temperature_recorded_on_Earth
8+ private const double HIGHEST_TEMPERATURE = 134.1 ;
9+
10+ // https://en.wikipedia.org/wiki/Highest_temperature_recorded_on_Earth
11+
512 public string Description { get ; set ; }
613 private double [ ] temp ;
714 public double [ ] Temp
@@ -11,34 +18,44 @@ public double[] Temp
1118 bool sortedSoFar = true ;
1219 int index = 0 ;
1320
21+ if ( value == null )
22+ {
23+ throw new ArgumentException (
24+ "Array of temperatures cannot be null."
25+ ) ;
26+ }
27+
1428 while ( index + 1 < value . Length && sortedSoFar )
1529 {
1630 if ( value [ index ] > value [ index + 1 ] )
1731 sortedSoFar = false ;
1832 index ++ ;
1933 }
34+
2035 if ( ! sortedSoFar )
2136 {
2237 throw new ArgumentException (
2338 "Your data is not sorted."
2439 ) ;
2540 }
26- foreach ( double i in value )
41+
42+ // At this point, we know the array is sorted (increasingly).
43+ // We can check only the first value against LOWEST_TEMPERATURE,
44+ // since we know all other values are greater.
45+ // Similarly, we can check only the last value against HIGHEST_TEMPERATURE.
46+ if ( value [ 0 ] < LOWEST_TEMPERATURE )
2747 {
28- if ( i < - 128.6 )
29- {
30- throw new ArgumentOutOfRangeException (
31- "That is colder than the coldest ever recorded on Earth!"
32- ) ;
33- // https://en.wikipedia.org/wiki/Lowest_temperature_recorded_on_Earth
34- }
35- else if ( i > 134.1 )
36- {
37- throw new ArgumentOutOfRangeException (
38- "That is hotter than the hottest ever recorded on Earth!"
39- ) ;
40- // https://en.wikipedia.org/wiki/Highest_temperature_recorded_on_Earth
41- }
48+ throw new ArgumentOutOfRangeException (
49+ "That is colder than the coldest ever recorded on Earth!"
50+ ) ;
51+ }
52+ else if (
53+ value [ value . Length - 1 ] > HIGHEST_TEMPERATURE
54+ )
55+ {
56+ throw new ArgumentOutOfRangeException (
57+ "That is hotter than the hottest ever recorded on Earth!"
58+ ) ;
4259 }
4360 temp = value ;
4461 }
0 commit comments