mercredi 18 septembre 2019

Class members for temporary state inside class

The following c++ class is given:

public class InvoiceHandler
{
    explicit InvoiceHandler(int invoiceId)
        : _invoiceId(invoiceId), _customerId(-1) 
    {
    }

    ~InvoiceHandler() {}

    void processInvoice()
    {
        selectCustomerId();

        if(customerExists())
        {
            selectCustomerAddress(); //in which the _customerId is needed agian
        }
    }

    void selectCustomerId()
    {
        QueryResult result = DbSelector.getResult(DbQuery::selectCustomerIdByInvoiceId(_invoiceId));

        if(!result.empty)
        {
            _customerId = result.at(0)["id"];
        }
    }

    bool customerExists() const
    {
        return _customerId > 0 ? true : false;
    }

    // some other functions which all needs the _customerId
    // for example: selectCustomerAddress();

    int _invoiceId;
    int _customerId;
}

I want to know if it's bad practise, to use some class members to save state during the execution of the class routines. In the given example above, I want to select the ID of a specific customer. In order to avoid parameters as (int customerId) on a few functions, i will save the ID as a class member. In my opinion this will make the "processInvoice()" function less understandable, because on the first glance it isn't visible which variables will be modified during the routines.

So my question is: if this pattern is bad practise, in which way should that functionality be implemented instead?

Aucun commentaire:

Enregistrer un commentaire