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 be 0 years old).
What I'd really recommend is using a hash instead:
class Person
constructor: ({@name, @age}) ->
new Person(name: "Peter", age: 19)
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With