2

I'm in the process of reading Code Complete 2 and learned that using global state is a no-no. What can I do to avoid using global state in this situation?

Some background information: I have two different methods (formAdded and formRemoved), each of which is called depending on whether an Add button is clicked or a Remove button is clicked. timesSignerIsRequired is a class variable, and these two methods are tied together by it, which seems bad. Here is my code.

formAdded: function(ev) {
    var formId = $(ev.currentTarget).data('formid');
    var self = this;
    var forms = Forms;
    $.each(forms, function(index, form) {
        if (form.id == formId) {
            //found this form - now find all signer ID's required with the current accountTypeId
            var requiredSigners = form[this.appModel.get('accountTypeId')];
            for (var i = 0; i < requiredSigners; i++) {
                self.timesSignerIsRequired[i] += 1;

                if (!signerIsRendered(i)) {
                    //render signer into view
                }
            }
        }
    });
}

formRemoved: function(ev) {
    var formId = $(ev.currentTarget).data('formid');
    var self = this;
    var forms = Forms;
    $.each(forms, function(index, form) {
        if (form.id == formId) {
            //found this form - now find all signer ID's required with the current accountTypeId
            var requiredSigners = form[self.appModel.get('accountTypeId')];
            for (var i = 0; i < requiredSigners; i++) {
                self.timesSignerIsRequired[i] -= 1;

                if (self.timesSignerIsRequired[i] <= 0) {
                    //remove signer from the view
                }
            }
        }
    });
}

Any suggestions?

1

1 Answer 1

1

timesSignerIsRequired is not global state, it's a field on your object. It's okay for the methods of an object to access the fields (including private fields) of that same object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.