Question

I'm trying to find a good way to document expected "interface" or "contract" of an object in JavaScript, e.g. which methods would be called, which properties are expected to be present and so on. I want it to be as close to code as possible (e.g. not in external documentation files).

Let's say I'm trying to design UI controls library in JavaScript. I would like to process a set of controls in a polymorphic way, e.g. call control.loadDataFromServer() regardless of whether it's a text field or dropdown or whatever. But some behavior may not be present in all types of controls, for example for editable controls I would call control.validate() or control.getValue() which won't happen for static text labels and such.

My main main goal is so a new developer trying to implement new control or modify the existing one can immediately understand what is possible to implement without having to sift through all the calling code.

In a statically typed language like C# or Java, I would have used interfaces like IControl and IEditableControl. Now, I know JavaScript is duck typed, but I do want to give some hints to further developers. I could provided dummy implementation in a control's prototype, but that solution seems dirty to me. What are my options?

Was it helpful?

Solution

In the end I decided to use something along the lines of this quacksLike solution http://fitzgeraldnick.com/weblog/39/.

For each logical "interface" I create an object which lists members along with very basic type indication using JS prototypes (String, Number, Function etc.). This interface objects are very easy to document with JSDoc (also to add missing information about method parameters).

When working with target objects, I check if object intends to support the "interface" and if so, I go ahead and call methods. It's not as safe as static typing, but good enough for me.

var interfaces = {
     ...
     validatable: {
         validate: Function,
         isValid: Boolean,
         getValidationMessages: Function
     }
     ....
}

...
if (typing.checkSupport(control, interfaces.validatable)) {
    control.validate();  
    if (!control.isValid) {
      ....
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top