“Decide which modules you want; partition the program so that data is hidden within modules.”
for example, the definition for a stack. the problems to solve:
for a stack, interface could be declared and used like this:
namespace Stack {
void push(char);
char pop();
}
void f() {
Stack::push(‘c’);
if (Stack::pop() != ‘c’) error(“impossible”);
}
define the interface in stack.h
:
namespace Stack {
void push(char);
char pop();
}
include the header file and implement the interface:
#include “stack.h”
namespace Stack {
const int max_size=200;
char v[max_size];
int top=0;
}
void Stack::push(char c) { /* check for overflow and push c */ }
char Stack::pop() { /* check for underflow and pop */ }
graphically, it looks like this:
in interface, define the exception (stack.h
):
namespace Stack {
...
class Overflow { };
}
in implementation, throw the exception when needed (stack.c
):
#include “stack.h"
namespace Stack {
…
void Stack::push(char c) {
if(top==max_size) throw Overflow();
// push c
}
}
use the exception capabilities in code (user.c
):
#include “stack.h”
void f() {
…
try {
while (true) Stack::push(‘c’);
}
catch (Stack::Overflow) {
// take appropriate action
}
}