JMU
Missing Values
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Review
Thinking About the Problem
The Pattern
Examples

Use a Default Value

javaexamples/programmingpatterns/MissingValues.java (Fragment: defaultmissing)
                total = 0.0;
        for (int i = 0; i < data.length; i++) {
            if (data[i] == null) {
                total += defaultValue; // Initialized elsewhere
            } else {
                total += data[i].doubleValue();
            }
        }
        average = total / (double) data.length;
        
Examples (cont.)

Ignore Missing Values

javaexamples/programmingpatterns/MissingValues.java (Fragment: ignoremissing)
                total = 0.0;
        n     = 0;
        for (int i = 0; i < data.length; i++) {
            if (data[i] != null) {
                total += data[i].doubleValue();
                n++;
            }
        }
        average = total / (double) n;
        
Examples (cont.)

Propagate Misisng Values

javaexamples/programmingpatterns/MissingValues.java (Fragment: propagatemissing)
                missing = false;        
        total = 0.0;
        for (int i = 0; i < data.length; i++) {
            if (data[i] == null) {
                missing = true;
                break; // No reason to continue iterating
            } else {
                total += data[i].doubleValue();
            }
        }

        if (missing) {
            result = null;
        } else {
            result = Double.valueOf(total / (double) data.length);
        }