jeromeetienne / better.js

a better javascript in javascript
http://betterjs.org
MIT License
156 stars 22 forks source link

Check that objects conform to specified Interfaces #102

Open joeytwiddle opened 9 years ago

joeytwiddle commented 9 years ago

For an example, I have a MMORPGame with Animals and Vehicles. Sheep inherits from Animal and Car inherits from Vehicle. But there is a crossover case, because Horse should provide the functionality of an Animal and a Vehicle!

Therefore I would like a way to ensure that my Horse objects meet the specifications for both the Animal and Vehicle types.

I think there might be two different ways that developers would want to do this:

    // If the Animal and Vehicle are "base classes" and have prototypes
    // with jsdoc-ed functions and properties:

    Bjs.implements(Horse, Animal.prototype);

    Bjs.implements(Horse, Vehicle.prototype);

or:

    // Animal and Vehicle base classes do not exist, so the developer
    // must explicitly specify the required interfaces:

    Bjs.implements(Horse, {
        makeAnimalSound: [ undefined, undefined ],
        doAnimalAction: [ String, Action ]
    });

    Bjs.implements(Horse, {
        moveForwards: [ Number, undefined ],
        turn: [ Number, undefined ],
        fuel: [ Number ]    // function taking 0 arguments, or a property
    });

    // (Those arrays are one way I imagined of specifying that
    // doAnimalAction takes one argument of type String
    // and returns an object of type Action.)

In the latter case, the developer may want to name those specification objects (e.g. AnimalInterface and VehicleInterface) so that he can apply them to other types (Sheep, Car) also.

(If Horse inherits directly from Animal (e.g. Horse.prototype = Object.create(Animal.prototype) or var horse = $.extend({}, new Animal);) then checking against the Animal interface would likely be redundant, unless functions (methods) are overridden.)

Edit: Worth noting how JSDoc defines types: http://usejsdoc.org/tags-typedef.html

It may be interesting to investigate how JSDoc represents such types within the code.