Monday, June 25, 2018

Return Whiplash

Confusing Code

Today I ran into some confusing code.

const wrapper = (element) => {
  if (this.state.myBoolean) {
    return (
      <TouchableWithoutFeedback onPressIn={this.handleAction}>
        <View
          style={{
            position: 'absolute',            
            top: 0,            
            bottom: 0,             
            left: 0,            
            right: 0,          
          }}
          pointerEvents="box-only">
          {element}
        </View>      </TouchableWithoutFeedback>    
     );  
  }
  return element;
};
return wrapper((
  <MyControl
    onCButtonPressed={this.onButtonPressed}
    activeButton={this.state.myBoolean}
  />
));

In this 20+ line of code there are tree separate returns.  Also the code doesn't go from top to bottom.  I felt like I had whiplash by the time I actually figured out what the code was doing.  I personally would have like something mare like this.

if (this.state.myBoolean) {
  return (
    <TouchableWithoutFeedback onPressIn={this.handleAction}>
      <View
        style={{
          position: 'absolute',          
          top: 0,          
          bottom: 0,          
          left: 0,          
          right: 0,        
        }}
        pointerEvents="box-only">
        <MyControl
          onButtonPressed={this.onButtonPressed}
          activeButton={this.state.myBoolean}
        />      </View>    </TouchableWithoutFeedback>  
   );
} else {
  return (
    <MyControl
      onButtonPressed={this.onButtonPressed}
      activeButton={this.state.myBoolean}
    />  );
}

It is about the same number of lines of code, but this I can follow easily.




No comments:

Post a Comment