index.md (1854B)
1 +++ 2 title = 'Modular programming' 3 +++ 4 # Modular programming 5 "Decide which modules you want; partition the program so that data is hidden within modules.” 6 7 ## Namespaces 8 for example, the definition for a stack. the problems to solve: 9 10 1. Provide a user interface (functions *push* and *pop*) 11 2. Ensure that the representation of the stack can only be accessed through these methods 12 3. Ensure that the stack is initialized before its first use 13 14 for a stack, interface could be declared and used like this: 15 16 ```cpp 17 namespace Stack { 18 void push(char); 19 char pop(); 20 } 21 void f() { 22 Stack::push(‘c’); 23 if (Stack::pop() != ‘c’) error(“impossible”); 24 } 25 ``` 26 27 ## Separate compilation 28 define the interface in `stack.h`: 29 30 ```cpp 31 namespace Stack { 32 void push(char); 33 char pop(); 34 } 35 ``` 36 37 include the header file and implement the interface: 38 39 ```cpp 40 #include “stack.h” 41 namespace Stack { 42 const int max_size=200; 43 char v[max_size]; 44 int top=0; 45 } 46 47 void Stack::push(char c) { /* check for overflow and push c */ } 48 char Stack::pop() { /* check for underflow and pop */ } 49 ``` 50 51 graphically, it looks like this: 52 53 ![screenshot.png](6d5dc15c08d82af46e93fec41ec22f28.png) 54 55 ## Exception handling 56 in interface, define the exception (`stack.h`): 57 58 ```cpp 59 namespace Stack { 60 ... 61 class Overflow { }; 62 } 63 ``` 64 65 in implementation, throw the exception when needed (`stack.c`): 66 67 ```cpp 68 #include “stack.h" 69 namespace Stack { 70 … 71 void Stack::push(char c) { 72 if(top==max_size) throw Overflow(); 73 // push c 74 } 75 } 76 ``` 77 78 use the exception capabilities in code (`user.c`): 79 80 ```cpp 81 #include “stack.h” 82 void f() { 83 … 84 try { 85 while (true) Stack::push(‘c’); 86 } 87 catch (Stack::Overflow) { 88 // take appropriate action 89 } 90 } 91 ```