#Each Component Side-Effect in a dedicated private method?

11 messages · Page 1 of 1 (latest)

livid birch
#

I recently find myself more and more getting into the habits of defining my side-effects in dedicated private methods that name the sort of side-effect for what it does.
That is very intentional to decouple each aspect of some sort of components behaviour from one another.

That leads to something like this (Uses ReactiveForms, so syncing external data into the form or changing somethin in field A based on something in field B happens via side-effects):

export class DirectDebitForm {
  ... bunch of injections ...
  ... bunch of fields ...

  directDebitForm = new FormGroup({
    ... the fields ...
  })

  constructor(){
    this.setupSetIbanAsInvalidOnInvalidBackendValidation();
    this.setupBackendIbanValidationOnIbanChange();
    this.setupNavigateOnSuccessfulRequest();
    this.setupSyncPaymentDataFromSelectedProductToForm();
  }

  public submitRequest(){...}

  private setupSetIbanAsInvalidOnInvalidBackendValidation(){...}
  private setupBackendIbanValidationOnIbanChange(){...}
  private setupNavigateOnSuccessfulRequest(){...}
  private setupSyncPaymentDataFromSelectedProductToForm(){...}
}

Any of these private functions basically is either a effect(() => {}) or pipe(takeUntilDestroyed()).subscribe(() => {}) call.

I kind of like how it strictly disentangles my side-effects, though some of them do interact with one another which I tend to mark with doc comments.
Any thoughts or opinions on that style? Suggestions?

rose fog
#

I'd do something similar

#

The constructor should remain readable

wide yew
#

I like to use private properties, not methods. I don't like to use constructor at all. But I use same technique with methods if initialization logic is too complex. Your example is good to read.

livid birch
wide yew
#

readonly #someEffect = effect(() => ...);
or
readonly #someEffect = this.methodWithEffect();

glossy plover
livid birch
#

Hmm, I think I'd stick with declaring effects in the constructor.
Semantically it just makes the most sense to me - the fact that it also causes some tooling is just a case in point for this.
Property assignments are for values you want to keep around and use.
Constructor is for setup-logic for the object in question, which in this case is setting up the side-effect-y logic.

But nice to know that apparently this kind of setup seems fairly normal and easily understood.

wide yew
#

Your approach is "normal" 🙂
I just don't like to write constructor. I didn`t use it at all after we got inject function. All additional setup I put into OnInit. But now they added effects. And I don't like to write a constructor only for them.

glossy plover
#

sometimes it is useful to cancel effects after they ran once, so declaring them in a field is necessary for that