How to make a good Coffee: best CoffeeScript coding practices

Clean, human-readable code is a crucial factor for all projects. Despite sugar syntax and all goodness that CS brings, writing good CoffeeScript can also be a challenge. Relying on my past experience with CoffeeScript I decided to make a set of straightforward rules, that works in development environment and saves us from unneeded mess in the code.

If you have some practice with JavaScript, you will find that most of the rules are very similar to those applying for JavaScript. But you also have to keep in mind that adding these few CoffeeScript extras, will make you proud of your consistent and pleasant code.

  1. Don’t skip braces when defining associate arrays.

    It’s frustrating and little time-taking for other programmers to figure out what structure it is.

          # Good
          myDict = {
            array : [1,2,3]
            name : 'Janet'
          }
    
          # Bad
          myDict =
            array : [1,2,3]
            name : 'Janet'
        
  2. Always use parens for function parameters.

    Even when you have a single parameter function to display some test text, use parens to keep your code readable and syntax continuous.

          # Good
          func('Some text', 12, $, undefined)
    
          # Bad
          func 'Some text', 12, $, undefined
        

    And if we combine it with object definition with implicit braces it gets really ugly:

          # Good
          func('Some text', 12, $, {a:1, b:2}, undefined)
    
          # Bad
          func 'Some text', 12, $, a:1, b:2, undefined
        
  3. Never forget the Camel Case.

    Start object’s name and every next words within it with capital letter. Variables begins with lowercase, but all following words are capitals.

          # Good
          class Someting
            veryImportantVariable = 'test'
    
          # Bad
          class someting
            veryimportantvariable = 'test'
            very_important_variable2 = 'test'
    
        
  4. Write constants and enums with capslock.

    Good habit form other procedural languages.

          # Good
          NUM = 5
          for i in [0...NUM]
            alert(i)
    
          # Bad
          num = 5
          for i in [0...num]
            alert(i)
        
  5. Start private functions and variables with underscore.

    Even though JavaScript doesn’t support privacy control (ECMAScript 5 introduces Object.defineProperty, but I haven’t seen many usage of that) if you want to accent that some parts shouldn’t be used publicly. This ancient-old JavaScript good practice is giving clearance for missing private statement.

          # Good
          class SomeClass
            _private = 5
    
            _privateFunc = ->
              alert('Hello')
    
          # Bad
          class SomeClass
            private = 5
    
            privateFunc = ->
              alert('Hello')
        
  6. Avoid constructing unneeded objects.

    It’s common practice to assign to newly created variables arrays and objects using new Array() and new Object(). Whereas object literal notation makes code cleaner, organised and more unified in its notation.

          # Good
          emptyObject = {
            a: 1
            b: 'three'
            c: undefined
          }
    
          emptyArray  = ['John', 'Doe']
    
          # Bad
          emptyObject = new Object()
          emptyObject.a = 1
          emptyObject.b = 'three'
          emptyObject.c =  undefined
    
          emptyArray = new Array()
          emptyArray[0] = 'John'
          emptyArray.push('Doe')
        

    If you are confused, when to use Array objects and when primitives, there is a general rule:

    When the property names are small sequential integers, you should use an array. Otherwise use an object.
  7. Comprehensions don’t solve everything.

    If you are a big fan of comprehensions included and pushed to limits in CoffeeScript I must warn you. Sometimes native JavaScript functions are faster and more efficient than the generated code, so use them thoughtfully.

    books = ['book1','book2','book3','book4']
    
    #Good
    concat = '<ul><li>' + books.join('</li><li>') + '</li></ul>'
    
    #Bad
    concat = '<ul>' 
      for book in books 
        concat += "<li>#{book}</li>"
    concat += '</ul>'
    	  
  8. Modularize your code.

    If you’re using jQuery or even pure JavaScript to develop complex logic, you probably have found yourself in a situation called Callback Hell, where you had many functions nested into another ones by callbacks. Avoid that by passing function names instead of using anonymous functions.

          # Good
          $('button').on('click', callAjax())
    
          callAjax: ->
            $.get({
              url: 'example.com'
              success: gotResponse(response)
    
          gotResponse: (response) ->
            alert(response.responseText)
    
          # Bad
          $('button').on('click', ->
            $.get({
              url: 'example.com'
              success: (response) ->
                alert(response.responseText)
          }))
      })
    }
        

    Example above is rather simple, but keeping your function at maximum level of 2-3 nesting levels will keep your code fairly readable.

CoffeeScript quality tool - best practices for writing good coffeescript

CoffeeLint

To enforce code quality use gaining a lot of popularity CoffeeLint library, that will ensure your code meets the standards of readability and structural correctness. CoffeeLint is a highly customizable port of popular jslint to CoffeeScript that allows you to take control over many factors of your code:

  • maintain indentation and line endings
  • control python-style like maximum line width
  • enforce parenes and braces
  • force Camel Case naming patterns
  • and many other

Weather you are going to choose settings I mentioned in this post, set your own set or use the default, it’s up to you, but your code will be kept consistent with CoffeeLint and writing a good CoffeeScript will be much easier.

Summary

Apply the rules above and I can guarantee, that you will never suffer form starring at your CoffeeScript code and figuring out what it’s hidden behind it.

If you have some rules that makes your code cleaner or you think that I have forgotten something in my post, please make a comment and improve this article.

If you read it, you should share it: