Of these alternatives, which is the best style for class-based programming in CoffeeScript?
# Alternative 1
class Person
constructor: (@name, @age) ->
new Person "Peter", 19
# Alternative 2
class Person
name: ""
age: 0
constructor: (@name, @age) ->
new Person "Peter", 19
# Alternative 3
class Person
constructor: (@name = "", @age = 0) ->
new Person "Peter", 19
# Alternative 4
class Person
constructor: (name, age) ->
@name = name ? ""
@age = age ? 0
new Person "Peter", 19
Hmm. #1 is nice and simple. #3 succinctly shows the expected format of the arguments (though the defaults don’t actually make sense—unless you’re expecting a person to be named
"", or to be0years old).What I’d really recommend is using a hash instead:
This frees you from having to memorize the order of the arguments, and makes your instantiation calls more self-documenting.
(I use this approach in some of the examples in CoffeeScript: Accelerated JavaScript Development.)