0

I've got a fairly large set of booleans I'm checking in javascript, and then using them to alter the state of a layout in my React app. The whole thing is unwieldy, difficult to read, inelegant, and feels terribly amateurish. I was wondering if there was a better pattern for handling something like this.

Example code snippet (in coffeescript). Replaced object variables with ints for brevity:

setNeeded = _.contains(sessionInitialStates, codingSession.state)
sessionUpdating = codingSession.state is 'UPDATING'
sessionFailed = codingSession.state is 'FAILED'
setExtended = _.contains extStates, codingSession.state
setInReview = _.contains(reviewStates, controlSet.state) or
  _.contains(controlSetSyncStates, controlSet.state)
sessionIsTagging = _.contains tagStates, codingSession.state
sessionComplete = codingSession.state is 'COMPLETE'
sessionIsNew = _.isEmpty(codingSession.state) or
  codingSession.state is 'CREATED'

commError = controlSet.state is 'COMMUNICATION_ERROR'
if setNeeded and @props.creds
  someVar = 1

else if _.contains(sessionInitialStates, codingSession.state) and
    controlSet.state is 'PROCESSING_FAILED'
  someVar = 2

else if codingSession.state is 'CONTROL_SET_GENERATION' and
    controlSet.state is 'SELECTION_FAILED' and @props.creds
  someVar = 3

else if !sessionIsTagging or !sessionComplete
  if _.isEmpty @props.connector
    someVar = 4

  else if !@props.creds
    someVar = 5

  else if sessionFailed
    someVar = 6

  else if sessionIsNew
    someVar = 7

  else if sessionUpdating
    someVar = 8

  else if setInReview and !setExtended
    someVar = 9
  • see also [Elegant ways to handle if(if else) else](http://programmers.stackexchange.com/questions/122485/elegant-ways-to-handle-ifif-else-else) – gnat Feb 19 '15 at 08:31

1 Answers1

0

When you notice large blocks of if/else, it usually means that your class or method is doing too much.

Instead of trying to rewrite the logic inside the method:

  • Ensure the method does one and one only thing.

  • Replace the class by multiple classes which inherit from a common one.

For practical examples, if you have an actual working piece of code but contains too much if/else statements, you may post it on CodeReview.SE.

Arseni Mourzenko
  • 134,780
  • 31
  • 343
  • 513