2

Coming from Scala, the lack of shadowing in CoffeeScript seems very odd. I wrote a demo.

object ZekeDemo extends App {

  val filterAll = (arr: Seq[String]) => {
    val saved = ArrayBuffer[String]()
    val removed = ArrayBuffer[String]()

    val filterDo = (arr: Seq[String]) => {
      val saved = for {item <- arr if item != "do"} yield item
      val removed = for {item <- arr if item == "do"} yield item
      (saved, removed)
    }

    val filterSo = (arr: Seq[String]) => {
      val saved = for {item <- arr if item != "so"} yield item
      val removed = for {item <- arr if item == "so"} yield item
      (saved, removed)
    }

    val addRemoved = (item: String) => removedBuff += item
    val addSaved = (item: String) => savedBuff += item

    for {item <- filterDo(arr)._1} { addSaved(item)}
    for {item <- filterDo(arr)._2} { addRemoved(item)}

    for {item <- filterSo(arr)._1} { addSaved(item)}
    for {item <- filterSo(arr)._2} { addRemoved(item)}

    (saved, removed)
  }

  val song = Seq("do", "re", "mi", "fa", "so")

  val s = filterAll(song)._1
  val r = filterAll(song)._2

  println("saved: %s, removed: %s".format(s.mkString(","), r.mkString(",")))

}

Now here's the same program in CoffeeScript:

filterAll = (arr) -> 

  saved = []
  removed = []

  filterDo = (arr) ->
    saved = ->
      item for item in arr when item != "do"
    removed = ->
      item for item in arr when item == "do"
    {"saved":saved(), "removed":removed()}

  filterSo = (arr) ->
    saved = ->
      item for item in arr when item != "so"
    removed = ->
      item for item in arr when item == "so"
    {"saved":saved(), "removed":removed()}

  addRemoved = (item) ->
    saved[saved.length] = item

  addSaved = (item) ->
    removed[removed.length] = item

  addRemoved item for item in filterDo(arr)["removed"]
  addSaved item for item in filterDo(arr)["saved"]

  addRemoved item for item in filterSo(arr)["removed"]
  addSaved item for item in filterSo(arr)["saved"]

  {"saved":saved, "removed":removed}

song = ["do", "re", "mi", "fa", "so"]

s = filterAll(song)["saved"]
r = filterAll(song)["removed"]

alert("saved: " + s + ", removed: " + r)

The "saved" that is declared as an array gets overwritten by the "saved" that references the for comprehension. Changing the variable names yields the expected output.

This seems very strange to me. A big part of the beauty of functional languages is not needing to know about outer scopes. If I write my "filterDo" function in another context (class|function|file), I believe I should be able to drop it into any other context where it is valid syntax and not have to worry about whether it is stepping on values from an outer scope.

A language that requires a developer to know all variable names in scopes outside the current scope discourages its developers from encapsulation. I could have fixed this bug by moving filterDo and filterSo to the outer scope. But this pollutes that scope's namespace and unnecessarily increases the surface area of the interface.

CoffeeScript's argument for not having a special syntax for shadowing variables is that you simply shouldn't do this kind of thing. Name your variables clearly. Because even if shadowing would be allowed it would be very confusing to have two variables with two different meanings with the same name, one in an inner scope and one in an enclosing scope.

I like this idea in principle, but in practice I don't believe languages should exhibit behavior this difficult to trace and resolve based on rules this subtle. Variable naming is a reflection of coding style, and style choices should not change the behavior of a program.

7
  • I suspect the issue is that you're mistaken as to what a scope is (I don't know coffeescript, so I don't know). For example, in python, all variables inside a function are in the same scope, so you can't have duplicate names within a function.
    – Marcin
    Jul 26, 2013 at 17:42
  • 1
    It wouldn't be as much of an issue if you could define immutable variables--then when you tried to assign again it'd be an error.
    – Rex Kerr
    Jul 26, 2013 at 17:49
  • 1
    This looks more like a rant than a question... Anyway, just move to ClojureScript instead—problem solved! :D
    – DaoWen
    Jul 26, 2013 at 18:28
  • 1
    I don't think the proper term is "shadowing" here. @DaoWen, doesn't sound like a rant to me.
    – pedrofurla
    Jul 26, 2013 at 20:38
  • 1
    @pedrofurla - "variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope." That sounds right to me. As for calling this a "rant"—I was more just pointing out that he didn't seem to actually ask a question anywhere, he just says "I don't like this choice made by CoffeeScript's designers."
    – DaoWen
    Jul 26, 2013 at 20:43

1 Answer 1

1

I think in practice you are not likely to come across this when writing small defs and classes, etc. and avoiding excessive/excessively generic globals (i.e. when you write "good code"). Your example seems especially contrived. Here is a simpler solution for your filterAll() function:

filterAll = (arr) ->
  saved: item for item in arr when item not in ['do', 'so']
  removed: item for item in arr when item in ['do', 'so']

I think it is reasonable to expect the coder to keep in his mind the variable names in a given scope—quite reasonable if you are writing small defs, classes, etc. per modern design standards. Even in your contrived example, once you understand the workings of the language, it is very easy to see the shadowing happening.

Furthermore, by default—unless you explicitly say otherwise—your compiled CoffeeScript files will be wrapped in closures automatically. So even if you write "bad code" and litter the top level with a bunch of generic var names, you will never accidentally stomp on other files' "global" vars (not global anymore considering the closure; global to the file).

I think the suggestion somewhere on the Interwebz of a := operator to explicitly denote assignment to a var in the outer scope of the same name is a sound suggestion (and by default compiler always would redeclare var in scope). However, at this point that would be a new major version for CoffeeScript because it would break tons of code written by people knowledgeable of the language and actually leveraging what you see as a problem. ;)

Hope this helps. It's an unexpected delight that the demo Scala app bears my name. I love Scala and CoffeeScript!

Not the answer you're looking for? Browse other questions tagged or ask your own question.