I'm going through the CoffeeScript book by Trevor Burnham, and I was curious as to what the best style is for a function I was writing.
In the book the author writes the function like so:
strToCoordinates = (input) ->
halves = input.split(',')
if halves.length is 2
x = parseFloat halves[0]
y = parseFloat halves[1]
if !isInteger(x) or !isInteger(y)
console.log "Each coordinate must be an integer."
else if not inRange x - 1, y - 1
console.log "Each coordinate must be between 1 and #{GRID_SIZE}."
else
{x, y}
else
console.log 'Input must be of the form `x, y`.'
I wrote my function like so:
strToCoordinates = (input) ->
halves = input.split(',')
if halves.length isnt 2
console.log 'Please enter coordinates in format: x,y'; return
[x, y] = (parseFloat s for s in halves)
unless isInteger(x) and isInteger(y)
console.log 'The coordinates must be integers.'; return
if not inRange(x, y)
console.log "Coordinates must be between 1 and #{GRID_SIZE}."; return
{x, y}
Is my use of just if
statements and using return
to stop the flow if the check fails okay style?
I like the fact that with this style the error messages are right after the check unlike with if/else
, and also you don't have to have large sections indented.