Black box programming and modularity

Black box programming is the embodiment of the concept of information hiding.

The goal is to provide an accurate description of what a routine does in terms of externally-visible behavior.

That should be all the information someone needs in order to use the routine correctly.

This reduces the information one needs to keep track of - the only time you need to consider the internal details of the routine is when actually implementing it, at all other times you (or any other developer) need only consider the black box description.

In black box programming, when using a function you don't care how the function is implemented.

With each function there should be a description detailing what the function does in terms of what goes in and what comes out.

In a practical sense, that is very often the only information you will be given about many of the routines you use.

The C libraries are a classic example - you use routines from these libraries all the time, without knowing how they are implemented.

Both the person calling a routine and the programmer who implemented it must be very careful, however.

Flawed blackbox example
  1. Doesn't describe side effects:
    int Sum(int aiData[], int iSize)
    /* returns the sum of aiData[0] through aiData[iSize-1] */
    {
       int i;
       for (i = 1; i < iSize; i++) aiData[i] += aiData[i-1];
       return(aiData[iSize-1]);
    }
    
  2. Doesn't describe the error handling:
    int GetRange(int lower, int upper)
    /* prompts the user to enter a value in the range
     * lower .. upper and returns that value
     */
    
  3. Gives unnecessary internal details:
    void ReverseString(char szInput[], int iSize)
    /* reverses the first iSize characters in the data string
     * by pushing them onto an internal stack, then pops them
     * off the stack overwriting szInput until the stack is empty
     */
    
Benefits of blackbox programming
Disadvantages of blackbox programming