user13406409
user13406409

Reputation:

How to improve flags in function?

I have the following code. I dislike this only aesthetically:

   public createDocument() {
        try {
            if (this.isOpenDialog) throw 'Dialog already opened!';
            this.loading = true;
            this.isOpenDialog = true;
            this.documentService.loadDocuments(this.application.reglamentid).then((response) => {
                this.documentService.setTypeDocuments(response.typedocuments);
                this.loading = false;
                this.documentDialogFormService.open({ title: 'Документ', application: this.application }).subscribe(() => {
                    this.isOpenDialog = false;
                });
            });
        } catch (e) {
            console.log('ERROR: ' + e);
        }
    }

As you can see there are two flags: this.loading and this.isOpenDialog. First controls opening dialog, The second indicates loading.

Is it possible somehow to improve it?

Upvotes: 0

Views: 47

Answers (1)

epascarello
epascarello

Reputation: 207557

The pattern you have is typically what people use since it is two distinct states for two different things. Reason why is the dialog could be loading and be shown at the same time. That means both could be true. Depending on what you do with it might make this the optimal solution.

If you want you could have one state that holds both. It might seem cleaner, but as you can see the check to see if it is opened is a bit more confusing since it has to check two states.

enum ModalStates {
  Closed,
  Loading,
  Opened
}

public createDocument() {
  try {
    if (this.modalState === ModalStates.Loading || this.modalState === ModalStates.Opened ) throw 'Dialog already opened!';
    this.modalState = ModalStates.Loading;
    this.documentService.loadDocuments(this.application.reglamentid).then((response) => {
      this.documentService.setTypeDocuments(response.typedocuments);
      this.modalState = ModalStates.Opened
      this.documentDialogFormService.open({
        title: 'Документ',
        application: this.application
      }).subscribe(() => {
        this.modalState = ModalStates.Closed
      });
    });
  } catch (e) {
    console.log('ERROR: ' + e);
  }
}

Upvotes: 1

Related Questions