Protip - return from exceptional conditions early

During a recent code interview, I noticed a React component with a render method written in the following (abbreviated) form,

1
2
3
4
5
6
7
8
9
10
11
12
render() {
return this.state.items.length > 0 ? (
<ComponentWithLotsOfProps
prop1={}
prop2={}
propN={}
...
/>
) : (
''
);
}

where ComponentWithLotsOfProps had at least a dozen props, some of which were not simple primitive values.

While there is nothing technically wrong with this render method, it could be better. It suffers from a few deficiencies.

First, ternaries are objectively difficult to read when they are not short. It is difficult to grok what the method actually produces because the whole ternary is returned, requiring the reader to do double work to find the “implicit” returns (there are two) rather than looking for the easily identifiable return keyword.

Second, one must read the entire method to know what gets returned if there are no items in state. Is it a component? Is it null? Is it an empty string? That is unknown until the whole method has been read.

Third, if additional conditions are required in future work to determine what will be rendered, they cannot easily be introduced in this method.

A better alternative is to omit the ternary, and explicitly return the exceptional condition values first.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
render() {
if (this.state.items.length === 0) {
return '';
}

return (
<ComponentWithLotsOfProps
prop1={}
prop2={}
propN={}
...
/>
);
}

Due to reduced nesting, this is far easier to read, and return values are also easily identifiable. If additional conditions must be evaluated in the future, modifying this method becomes much simpler:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
render() {
if (this.state.items.length === 0) {
return '';
}

if (this.state.items.length == 1) {
return (<SingleItemComponent item={this.state.items[0]} />);
}

return (
<ComponentWithLotsOfProps
prop1={}
prop2={}
propN={}
...
/>
);
}

As with most things in programming: the simpler, more explicit, the better.