Question

Lets say I have a void method/function to check the arguments of the program:

void check(int argc, String argv){
    //some irrelevant code
}

In this function I have some checks to validate the correctness of the arguments. For example if there are too much or if they're not recognized.

Should I just quit the program in this function as in example 1, or should I give it a return value and quit it in main()?

Example 1

void check(int argc, String argv){
    if(argc > 4){
        print("Too many arguments!");
        exit(-1);
    }
    //code
}

Example 2

int check(int argc, String argv){
    if(argc > 4){
        print("Too many arguments!");
        return -1;
    }
    //code
}

int main(int argc, String argv){
    if(check(argc, argv) == -1){
        return -1;
    }
}
Was it helpful?

Solution

Leave it to your main function to quit the program. Your check function's sole purpose should be to check parameters and return a valid / invalid state. IMHO it shouldn't even be responsible of printing the end user message.

The least responsibility you give to a method, the easier it will be to read, reuse, document and test.

OTHER TIPS

I'm hesitant to terminate operation in a method other than the main method, simply because it makes it harder to reuse the operation without modification, either in your application or in another application. I would prefer returning an error condition from the method that can be checked by the caller or throwing an exception or whatever similar mechanisms your language or style guide calls for.

One exception could be helper functions for your main method. For example, if you've encapsulated your main routine by itself in a single file and have methods that exist only to initialize and launch your application, then I would consider it acceptable to exit from these methods if execution cannot proceed.

Do 1 thing at a time in your functions, that way you can document and reuse them.

So if your check function simply checks a value and returns a boolean, you can reuse it anywhere you have similar requirements.

If it exits, then it is only valuable in this 1 program.

As a best practice, exiting within functions is not a good thing to do, there are cases where you will do this (generally on unrecoverable error) but unless there is an absolute, obvious need to do so, keep exiting only at the end of main().

In my opinion only the main() function should be responsible for stopping the program. Having a separate function to check the validity of the arguments makes this part easier to test. And think about what happens if your program expands; if you suddenly had half a dozen methods that could potentially cause the program to exit then I think you would run into problems.

Licensed under: CC-BY-SA with attribution
scroll top