Skip to content

Instantly share code, notes, and snippets.

@sebs
Last active August 29, 2015 14:03
Show Gist options
  • Save sebs/9d3287b9aabdb1ec0678 to your computer and use it in GitHub Desktop.
Save sebs/9d3287b9aabdb1ec0678 to your computer and use it in GitHub Desktop.
Blog Post about switch refactoring to events

I see this kind of code a lot of time and more importantly: I have written a lot of these statements myself

Class Activity 
  doSomethingThatIsCoolToday: (day) ->
    switch day
    when 'Mon' then go 'work'
    when 'Tue' then go 'relax'
    when 'Thu' then go 'iceFishing'
    else go 'i dont know what to do. Bored'

What is the intention of this code?

  • map the input 'day' to a action
  • define what the 'action is'
  • define a error case when no valid input is given

Anyway, this has a set of problems. What are these problems?

Lets talk about coupling

TL;TR How much do Objects and Methods know from each other?

Lets talk about cohesion

TL;TR Does this code belong together, in terms of do all the functions work on the same kind of narrowly defined task?

  • mapping a day to a action is one thing
  • defining what the specific action is: as well
Class Activity
  constructor: () ->
    @emitter = new EventEmitter
  doSomethingThatIsCoolToday: (day) ->
    @emitter.emit day, {some: 'more', info: true}
  subscribeToThingsDone: (day, listener) ->
    @emitter.on event, listener

A concrete usage would look like

activity = new Activity
activity.on 'day', ->
  go 'work'

Some clear wins over the switch case

  • the concrete implementation of WHAT you do can be set in a different place
  • no more switch case if things
  • adding more functionality can be done in extra calls to on and thus different methods

The downs

  • Sometimes harder to debug
  • Code can add event listeners in any part of the program
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment