CS253: Software Development with C++

Spring 2023

Divide And Conquer

Show Lecture.DivideAndConquer as a slide show.

CS253 Divide And Conquer

Julius Caesar, thinking “Veni, vidi, vici

Horror Stories

Divide and Conquer

Programming

Programming

Example

Consider the program grep:

How not to do it

    int main(int argc, char *argv[]) {
        parse options;
        if (no arguments)
            for (each line in standard input)
        	if (line matches the pattern or maybe if it doesn’t) {
        	    display the line number, if required;
        	    display the line according to the options;
        	    if (only list the first match)
        		break;
        	}
        else  // 🦡
            for (int i=1; i<argc; i++)
        	for (each line in that file)
        	    if (line matches the pattern or maybe if it doesn’t) {
        		display the line number, if required;
        		display the line according to the options;
        		if (only list the first match)
        		    break;
        	    }
    }

Not DRY, and would really be much longer. grep has over 40 options.

How to do it

    int main(int argc, char *argv[]) {
        parse_options(argv);
        if (no arguments)
            process_stream(cin);
        else
            for (int i=1; i<argc; i++)
        	process_file(argv[i]);
    }

There—that’s manageable.

Break it down

    void process_file(const string &filename) {
        ifstream in(filename);
        if (!in) {
            complain;
            exit(1);
        }
        process_stream(in);
    }

No duplication of code: process_file() uses process_stream().

Break it down

    void process_stream(istream &in) {
        for (string line; getline(in, line); )
            if (match_pattern(line)) {
        	display_line(line);
        	if (only list the first match)
        	    break;
            }
    }

Objections

This will make my program longer!
So? Are you running out of disk space?
This will slow my program down!
Really? I’ll bet that you can’t measure the difference, with all this file I/O and regular expression matching going on.
I can understand it just fine if it’s all in main()! Can’t you ?
Aren’t you masculine. Yes, it’s possible to do that way, but, …, why ? Save your effort for the tasks that need  to be difficult.