JMU
Checklists
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Review
Thinking About the Problem

Determining if One Item has been Completed

javaexamples/programmingpatterns/checklist/Fragments.java (Fragment: 0)
                boolean done  = false;        
        for (int a = 0; a < accomplished.length; a++) {
            if (accomplished[a].equals(checklist[index])) {
                done = true;
                break;
            }
        }
        
Thinking About the Problem (cont.)
Thinking About the Problem (cont.)

One Incorrect Solution

         
Thinking About the Problem (cont.)

Another Incorrect Solution

         
The Pattern

An Inflexible (but Simple) Solution

javaexamples/programmingpatterns/checklist/Inflexible.java (Fragment: 0)
            /**
     * An n out of n checklist.
     *
     * @param checklist  The checklist
     * @param accomplished  The array of accomplished items
     * @return true if the Checklist is satisfied; false otherwise
     */
    private static boolean checkFor(String[] checklist, String[] accomplished) {
        boolean checked;
        for (int c = 0; c < checklist.length; c++) {
            checked = false;

            for (int a = 0; a < accomplished.length; a++) {
                if (checklist[c].equals(accomplished[a])) {
                    checked = true;
                    break;
                }
            }            
            if (!checked) return false; // An item was not accomplished
        }
        return true; // All items were accomplished
    }
        
The Pattern (cont.)

A Flexible Solution

javaexamples/programmingpatterns/checklist/Elegant.java (Fragment: outerChecklist)
            /**
     * An m (required) out of n (size) checklist.
     *
     * @param checklist  The checklist
     * @param accomplished  The array of accomplished items
     * @param needed     The required number of checklist items
     * @return true if the checklist is satisfied; false otherwise
     */
    private static boolean checkFor(String[] checklist, String[] accomplished, 
                                    int needed) {
        int       count;        
        count = 0;
        for (int c = 0; c < checklist.length; c++) {
            for (int a = 0; a < accomplished.length; a++) {
                if (checklist[c].equals(accomplished[a])) {
                    count++;
                    
                    if (count >= needed) return true;
                    else                 break;
                }
            }
        }
        return false; // Not enough items were accomplished
    }
        
Examples for You to Trace