Hiding Details
In any language that a programmer uses, implementing an algorithm may be seriously corrupted by deliberate or inadvertant changing of some variable used with the algorithm. As programs grew larger the ability to know all parts of the program grew smaller until today that even modestly sized programs contain hundreds of variables. Think about the last Man/Machine Interface program you wrote and tell me you know each and every variable name in the program and what it does. So hiding details is useful for program security.
Now consider the program itself. How many times will you want to use the words "open", "close" or "initialize" as a function name in the public interface of some module. Now the c++ class allows us to do just that. Furthermore, much of data used in the algorithm may be hidden from view outside of the object. Now we would know that the algorithm would not behave incorrectly because of a distrubance code outside of the class. Any failure of the algorithm could be blamed on the code inside class.
An example might make this clearer. Suppose we want to describe several nodes in a network. Each node in the network has three parameters:
- Name
- Ipv4 address
- Ipv6 address
- container of nodes
- number of nodes in container
- indicator of current node
Let's name the container class, Nodes and the single node class Node. The node is the interesting thing, the container class not so much. But, we do need to initialize the container class, add a node to the container, perhapse delete a node from the class, find a specific node by node or address, and visit each and every node in the container. Here is a possible Node class:
Here is a possible container class, Nodes:class Node {
public:
String name;
String ipv4;
String ipv6;
}
So all the data used by the container class is protected. The methods (functions) are able to reliably store, find and delete the nodes from the data structure. Furthermore, if 10 items are not sufficient then another data structure may be substituted and the outside world need not know and no code outside will need to be changed. An expanding array, a linked list or a hash table could replace the static array.class Nodes {
private:
int curNode;
int noNodes;
Nodes nodes[10];
public:
Nodes() : noNodes(0), curNode(-1) {}
void add(node& n);
Node* find(String& name);
bool delCurNode();
Node* startLoop();
Node* nextNode();
}
One more point about these two classes. We probably will only instantiate one container class, i.e. one container object but there are at least 10 instances of the Node class, i.e. 10 Node objects. So the notion of hiding is a property of the class declaration regardless of the number of objects created by using the class.