This question deals with CoffeeScript but the same issues still apply to JavaScript. Consider this example:
class Parent
func: ->
alert @member
class Child extends Parent
constructor: ->
@greet()
greet: ->
@member = 'hello!'
@func()
Parent is useless on its own. (new Parent).func() returns undefined.
My questions are:
-
Is there anything wrong with defining classes like
Parentwhich just provide common functions and attributes to child classes?Parentcould be a complex class in its own file, providing functionality to classes far down in the prototype chain. Without documentation this could be confusing. -
In
Child.greet, we dynamically addmemberto a Child object. Is there anything wrong with adding new members to objects without first initializing them in the constructor? Is it better to doconstructor: -> @member = null; @greet()? That way, the next programmer knowns what members the object will have and will avoid issues with undefined variables. The flip side is the code will have more noise which JavaScript doesn’t necessitate. -
Finally, is there a source code which is a good example of idiomatic OOP in CoffeeScript?
Regarding your first question, no, i don’t think there’s anything inherently wrong with doing that. I’d say it’s a case of the template method pattern (using a property access instead of a method, but basically the same). I does add some complexity to your code structure, so, in case it can be resolved in a simpler way, i’d recommend going with the simpler solution.
About not initializing member variables in the constructor, well, ideally the constructor should leave the object in a usable state, that doesn’t necessarily mean initializing every possible member variable. For that particular code snippet, adding
@member = nulladds nothing in my opinion. An example of a bad constructor would be one that requires the user to do more stuff than instantiating the object before using it, something like:I don’t know about good sources for idiomatic OO CoffeeScript. I think Smooth CoffeeScript is a good book to learn the language, it has a chapter about OO, but i don’t if it is thorough enough.