2

As mentioned in the interface section of 'Programming javascript applications' you can implement interfaces with stampit. When reducing the unnecessary stuff from the example, I end up with something like this:

const fooBarInterface = 
    stampit()
        .methods(
            {
                foo: () => {
                    throw new Error('connect not implemented'); 
            },
                bar: () => {
                    throw new Error('save not implemented');
            }
        }
    )

Excerpt from an interface definition:

If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

So now putting the interface in use

const fooBarImplementation = 
    stampit()
        .compose(fooBarInterface)
        .methods(
            {
                foo: () => {
                    // implement me
                }
            }
        }
    )

Now, when composing an object from the stamp, there should be an error because bar is not implemented by fooBarImplementation. It isn't, and I fear that it's pretty hard to get something like this in place because there is no compiling at all.

So, my question is: Am I doing it wrong or is this half baked thing what Eric Elliott calls an 'Interface'?

Marc Dix
  • 1,864
  • 15
  • 29
  • 1
    I just wrote a small stamp that checks the methods for implementation: https://github.com/mdix/interface-check-stamp – Marc Dix Nov 18 '15 at 09:10

1 Answers1

0

The module you've created is great! You really know stampit well.

Although, in JavaScript I would recommend to go a different path. Namely, check if method is present.

if (obj.bar) kangaroo.bar();

And remove the fooBarInterface entirely. But if you need to check the method presence while creating the object, then you should do it similar to your module.

var ValidateFooBar = stampit()
  .init(function() {
    if (!_.isFunction(this.foo)) throw new Error('foo not implemented');
    if (!_.isFunction(this.bar)) throw new Error('bar not implemented');
  });

And use it:

const fooBarImplementation = stampit()
  .compose(ValidateFooBar)
  .methods({
    foo: function() {
      // implement me
    }
  });

Will throw: Error: bar not implemented

Vasyl Boroviak
  • 5,959
  • 5
  • 51
  • 70