Lazy evaluation postpones an expensive calculation until its result is needed. A hybrid Date representation stores year-month-day values and Julian day numbers, converting between them only when a getter or date-arithmetic method requires the corresponding form. section 5.3.3
The Date implementation applies the technique through synchronized representations:
- Getters validate the year-month-day representation before returning year, month, or day. section 5.3.3
- Date arithmetic validates the Julian representation before adding days or calculating differences. section 5.3.3
- Validity flags prevent repeated conversions after a representation has been synchronized. section 5.3.3
Listing 5.12 (Program 5.4 DateArithmetic-3): date.py (1 of 2; efficient hybrid)
class Date:
...
def __init__(self, *parms):
if len(parms) == 1:
self._julian = parms[0] #1
self._ymd_valid = False #1
self._julian_valid = True #1
else:
self._year, self._month, self._day = parms #2
self._ymd_valid = True #2
self._julian_valid = False #2
def _validate_ymd(self): #3
if not self._ymd_valid:
self._year, self._month, self._day = \
Date._to_ymd(self._julian)
self._ymd_valid = True
def _validate_julian(self): #4
if not self._julian_valid:
self._julian = \
Date._to_julian(self._year, self._month, self._day)
self._julian_valid = True
Inspect the validation methods that convert representations only when their values become necessary. section 5.3.3












