0
\$\begingroup\$

Hello all I am using some typescript reactive forms, like this

this.formControls.propertyType.valueChanges.subscribe((value: string) => {
  if (!this.currentSelectedType) {
    this.currentSelectedType = value;
  } else {
    if (this.currentSelectedType === CbcPropertyType.Other) {
      this.openModal();
      this.currentSelectedType = value;
    } else {
      this.currentSelectedType = value;
    }
  }
});

Is there some better solution for this part of the code, thanks

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Jeff Atwood calls this structure Arrow Code and describes it in his blog post "flattening arrow code".

The nested structure can be avoided by adding retrun statements, like:

this.formControls.propertyType.valueChanges.subscribe((value: string) => {
  if (!this.currentSelectedType) {
    this.currentSelectedType = value;
    return;
  } 

  if (this.currentSelectedType === CbcPropertyType.Other) {
    this.openModal();
    this.currentSelectedType = value;
    return;
  }

  this.currentSelectedType = value;
});

When we look closely we can see, that all three branches do nearly the same. Only if the currentSelectedType equals CbcPropertyType.Other a modal should open.

We can reduce the code to:

this.formControls.propertyType.valueChanges.subscribe((value: string) => {
  if (this.currentSelectedType === CbcPropertyType.Other) {
    this.openModal();
  }

  this.currentSelectedType = value;
});
```
\$\endgroup\$

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.