Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which style is best for class-based programming in CoffeeScript?

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
like image 783
ajsie Avatar asked May 12 '26 20:05

ajsie


1 Answers

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.)

like image 135
Trevor Burnham Avatar answered May 15 '26 10:05

Trevor Burnham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!