Working with interfaces

Interfaces are contracts. An interface defines what some consumer needs from some class instance in order to work with it. Or it can be understood as a contract that a class must full-fill in order to be consumed by some consumer.

In a real-world scenario, that means an interfaces defines properties and methods that some class must implement.

jOOPL ports this idea to JavaScript and implements it with $interface and $interfacedef keywords.

An important point is jOOPL supports multi-inheritance for interfaces.

Interface naming convention

The identifier of an interface will be an upper-cased I letter and a pascal-cased name. Examples of the convention:
  • ICallable
  • IInsertable
  • IDomBrowsable
  • ISearchableByKey

1. Defining/declaring interfaces

Interfaces are defined/declared using the $interfacedef keyword and constructor.

Arguments to the required input parameters of $interfacedef constructor are provided with an object map (i.e. an anonymous object).

Here is a parameter table and descriptions:

Parameter name Description
$members An object map of properties/accessors and methods that some class or another interface must implement
$implements An array of interfaces that the declaring interface must implement too (interface inheritance).


The members defined by an interface provide an empty body. That is because jOOPL only requires the member signatures in order to ensure that some class implements the whole interface.

A sample interface

$namespace.register("MyNamespace", function () {
    this.ITestable = $interfacedef({
        $members: {
            test: function () { }
        }
    });
});

A sample interface with multi-inheritance

$namespace.register("MyNamespace", function () {
    this.ITestable = $interfacedef({
        $members: {
            test: function () { }
        }
    });

    this.IExecutable = $interfacedef({
        $members: {
            test: function () { }
        }
    });

    this.IInvokable = $interfacedef({
        $members: {
            test: function () { }
        },
        $implements: [this.ITestable, this.IExecutable]
    });
});

2. Checking if a class or object implements an interface

Once a class implements one or more interfaces, jOOPL provides an approach to check if an object or a given class implement an interface: the $implements function:

if($implements(someInstance, $global.MyNamespace.IExecutable)) {
      // Do some stuff if someInstance implements the whole interface!
}

Last edited Apr 6, 2013 at 1:41 PM by MFidemraizer, version 20

Comments

No comments yet.