1

I'm working on an Angular2 app and I often encounter the following problem: I have an object of some type that could possibly be undefined, and I need to assign properties of that object to multiple variables or another object properties, so I usually use optional chaining operator to check whether object exists like that:

observable$.subscribe((object: SomeInterface | undefined) => {
    this.var1 = object?.prop1;
    this.var2 = object?.prop2;
    this.var3 = object?.prop3;
});

But I always feel that I'm doing a lot of unnecessary checks, and I think that maybe I should use if statement in this case like so:

observable$.subscribe((object: SomeInterface | undefined) => {
    if (object) {
        this.var1 = object.prop1;
        this.var2 = object.prop2;
        this.var3 = object.prop3;
    }
});

But in this case I'm feeling like it can be harder to read code? So I guess my question is what is more efficient (I think second option?) and what's better to use from code readability standpoint?

tsinevik
  • 11
  • 1
  • 2
  • I prefer the second approach for readability. Second is also probably more efficient, but that's almost certainly irrelevant – CertainPerformance Aug 21 '21 at 16:14
  • _"I'm feeling like it can be harder to read code"_ - What's complicated about that `if`? – Andreas Aug 21 '21 at 16:14
  • Maybe I gave a bad example, but if we need to assign to fourth variable some subproperty like `this.var4 = object.prop4.subprop1` and so on, than we need to write additional `if` statements and code can become more complex? Or maybe I'm just making it up – tsinevik Aug 21 '21 at 16:19
  • 1
    I think a single if is fine, but I would avoid having multiple if statements. In my opinion the optional chaining approach preferable when you are dealing with deeply nested properties which are independent. Ie. some might be present and others might not be. In the case where you either have all or none, that’s where I find the single if group to be more readable. – Linda Paiste Aug 21 '21 at 16:38

2 Answers2

1

Definitely go for the second approach. One if statement is way better than checking for each prop.

If you are worried about readability you can write it in following way

object && (this.var1 = object.prop1, this.var2 = object.prop2, this.var3 = object.prop3);

But from my point of you the readability is same.

0

I know this might not be what you want in this case but i always like to advocate the use of RxJS pipe operators.

observable$.pipe(filter(o => !!o)).subscribe((object: SomeInterface) => {
    this.var1 = object.prop1;
    this.var2 = object.prop2;
    this.var3 = object.prop3;
});
Tobias S.
  • 21,159
  • 4
  • 27
  • 45