vendredi 27 novembre 2015

Parsing commands using map

Problem statement:

Given the interactive input, call the appropriate methods on appropriate objects (Bank, BankRegister, BasicAccount, etc...).

input (each command on a separate line):

create_bank <bank_name>\n
create_customer <bank_number> <customer_name>\n
create_account <bank_number> <customer_number>\n
deposit <amount> <account_number>/<bank_number>\n
etc...

Proposed solution:

#include <functional>

bool create_bank(const string& arguments){
    const string& bankName = arguments; //no need to parse here
    bankRegister.registerBank(new Bank(bankName,
                                       &bankRegister)); //can't access bankRegister!
    return true;
}

int main(){
    map<string, function<bool (string)>> commands;
    commands.emplace("create_bank",create_bank);
    ...
    BankRegister bankRegister;

    string command, arguments;
    cin>>command;
    getline(cin, arguments);
    commands[command](arguments);
    ...
}

Why it does not work:

  1. The bankRegister object can't be accessed from the functions. I might pass it by constant reference to the functions, but only some functions need it. I was thinking of making its members (m_banks, m_next_bankNumber) static, but then I would have to make them public, which is probably a bad design decision.
  2. Where should the argument parsing happen? Is it OK this way?
  3. What should the return value represent?

    a) arguments parsed successfully

    b) arguments parsed successfully and command executed successfully

    I use the exceptions for some of the errors, but some are silent except for cerr.

  4. Could I use variadic functions here to parse the arguments?

  5. Is there something else you would improve?

Aucun commentaire:

Enregistrer un commentaire