OOC:en:3.5 Information Hiding

来自 ChinaUnix Wiki

Applying what we have learned thus far, we do not reveal the structure of a node at all. Instead, we place some declarations in a header file value.h:

   const void * Add; 
       ... 
   void * new (const void * type, ...); 
   void process (const void * tree); 
   void delete (void * tree); 

Now we can code sum() as follows:

   #include "value.h" 
   static void * sum (void) 
   { void * result = product(); 
     const void * type; 
     for (;;) 
     { switch (token) { 
       case ’+’: 
           type = Add; 
           break; 
       case ’—’: 
           type = Sub; 
           break; 
       default: 
           return result; 
       } 
       scan(0); 
       result = new(type, result, product()); 
     } 
   }

product() has the same architecture as sum() and calls on a function factor() to recognize numbers, signs, and a sum enclosed in parentheses:

   static void * sum (void); 
   static void * factor (void) 
   { void * result; 
     switch (token) { 
     case ’+’: 
         scan(0); 
         return factor();
     case ’—’: 
         scan(0); 
         return new(Minus, factor()); 
     default: 
         error("bad factor: ’%c’ 0x%x", token, token); 
     case NUMBER: 
         result = new(Value, number); 
         break; 
     case ’(’: 
         scan(0); 
         result = sum(); 
         if (token != ’)’) 
             error("expecting )"); 
     } 
     scan(0); 
     return result; 
   }

Especially in factor() we need to be very careful to maintain the scanner invariant: token must always contain the next input symbol. As soon as token is consumed we need to call scan(0).

个主工具