5 Sept 2012

Anonymous classes

I must apologise for the long silence. Every time I make a plan of what I want to tell about in some blog, I miss lots of things I could tell but didn't because they are not planned, and do not tell about planned things because do not have an appropriate mood for that. Anyway, I've decided to post here what I want to in every moment, though it will be a mess.
I had to work much with classes in CoffeeScript for last few days. The main problem of my work is that I convert Java code to CoffeeScript. Thus I need to have all the Java-like constructions in my disposal: anonymous classes, interfaces, nested classes, enums...
To be honest, interfaces are absolutely useless in CoffeeScript (as you can never declare a typed variable) but in Java they sometimes contain constants that you may need in other parts of code. So, making interface in CoffeeScript is pretty simple - you just declare the class with all the necessary fields (and empty method - if you wish to make your code more readable and self-documented).
The interesting thing I found out several days ago is that CoffeeScript allows making anonymous classes quite easily, though I failed to find this option in its' official docs (http://coffeescript.org/).
Let's take the same example as in the previous post but with anonymous classes:
class Animal
  name: undefined
  @numberOfRegisteredAnimals: 0

  constructor: (@name) ->
    Animal.numberOfRegisteredAnimals += 1

  @printNumberOfRegistedAnimals: () ->
    console.log "The number of registered animals is equal to",
      Animal.numberOfRegisteredAnimals

  sayName: () ->
    console.log "My name is " + @name + ", " + @voice()

Animal.printNumberOfRegistedAnimals()
cat = new (class extends Animal
  voice: () ->
    return "meow!!!"
)("Kuzya")
cat.sayName()
Animal.printNumberOfRegistedAnimals()
dog = new (class extends Animal
  voice: () ->
    return "woof!!!"
)("Sharik")
dog.sayName()
Animal.printNumberOfRegistedAnimals()
Take a look at lines 16-19 and 22-26: instead of declaring child classes as we did in previous sample, we create anonymous classes with added method @voice and call their constructors. You can check that the output will be exactly the same as in previous example.

To be continued...

No comments:

Post a Comment