DEV Community

Nicholas Cloud
Nicholas Cloud

Posted on

Protip - return from exceptional conditions early

This article was originally posted on nicholascloud.com.


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

render() {
  return this.state.items.length > 0 ? (
    <ComponentWithLotsOfProps
      prop1={}
      prop2={}
      propN={}
      ...
    />
  ) : (
    ''
  );
}
Enter fullscreen mode Exit fullscreen mode

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.

render() {
  if (this.state.items.length === 0) {
    return '';
  }

  return (
    <ComponentWithLotsOfProps
      prop1={}
      prop2={}
      propN={}
      ...
    />
  );
}
Enter fullscreen mode Exit fullscreen mode

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:

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={}
      ...
    />
  );
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)