One Task per Function

How strict do you need to be when creating functions, in terms of only doing one thing per function?

For example, in a game of TicTacToe I made, I had this member function:
1
2
3
4
5
void TicTacToe::chooseX_OR_O()
{
    cout << "Choose your symbol (X || O): ";
    cin >> choice;
}

As you can see, the function performs two tasks. It displays text and receives user input. For a function like this, it seems unnecessary to me to break the two tasks up.

What advice can you give regarding the modularity of functions?
The concept is a single task, so your function is correct.

If you tell your kid to "ask the neighbors if they'll eat with us tonight", your kid has to both go over and speak the question, and then listen to the answer before reporting the answer to you. Yet we consider it to have been a single task.

Don't break abstractions down too far. Asking for input and receiving input are a single task.

Parsing the answer you get is often a separate task, but for very simple inputs, you can even include that as part of the task:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void TicTacToe::choose_X_or_O()
{
    while (true)
    {
        // ask for the input
        cout << "Choose your symbol ('X' or 'O'): ";

        // get the input
        string s;
        getline( cin, s );

        // validate the input
        if (s.length() == 1)
        {
            choice = toupper( s[0] );
            if ((choice == 'X') or (choice == 'O')) return;
        }
    }
}

This performs the (single) task of getting an 'X' or an 'O' from the user.

Hope this helps.
Thank you Duoas, you've made the concept clearer to me.
Topic archived. No new replies allowed.