Programming in D – Tutorial and Reference
Ali Çehreli

Other D Resources

Interfaces

The interface keyword is for defining interfaces in class hierarchies. interface is very similar to class with the following restrictions:

Despite these restrictions, there is no limit on the number of interfaces that a class can inherit from. (In contrast, a class can inherit from up to one class.)

Definition

Interfaces are defined by the interface keyword, the same way as classes:

interface SoundEmitter {
    // ...
}

An interface is for declaring member functions that are implicitly abstract:

interface SoundEmitter {
    string emitSound();    // Declared (not implemented)
}

Classes that inherit from that interface would have to provide the implementations of the abstract functions of the interface.

Interface function declarations can have in and out contract blocks:

interface I {
    int func(int i)
    in {
        /* Strictest requirements that the callers of this
         * function must meet. (Derived interfaces and classes
         * can loosen these requirements.) */

    } out {    // (optionally with (result) parameter)
        /* Exit guarantees that the implementations of this
         * function must give. (Derived interfaces and classes
         * can give additional guarantees.) */
    }
}

We will see examples of contract inheritance later in the Contract Programming for Structs and Classes chapter.

Inheriting from an interface

The interface inheritance syntax is the same as class inheritance:

class Violin : SoundEmitter {
    string emitSound() {
        return "♩♪♪";
    }
}

class Bell : SoundEmitter {
    string emitSound() {
        return "ding";
    }
}

Interfaces support polymorphism: Functions that take interface parameters can use those parameters without needing to know the actual types of objects. For example, the following function that takes a parameter of SoundEmitter calls emitSound() on that parameter without needing to know the actual type of the object:

void useSoundEmittingObject(SoundEmitter object) {
    // ... some operations ...
    writeln(object.emitSound());
    // ... more operations ...
}

Just like with classes, that function can be called with any type of object that inherits from the SoundEmitter interface:

    useSoundEmittingObject(new Violin);
    useSoundEmittingObject(new Bell);

The special emitSound() function for each object would get called and the outputs of Violin.emitSound and Bell.emitSound would be printed:

♩♪♪
ding
Inheriting from more than one interface

A class can be inherited from up to one class. There is no limit on the number of interfaces to inherit from.

Let's consider the following interface that represents communication devices:

interface CommunicationDevice {
    void talk(string message);
    string listen();
}

If a Phone class needs to be used both as a sound emitter and a communication device, it can inherit both of those interfaces:

class Phone : SoundEmitter, CommunicationDevice {
    // ...
}

That definition represents both of these relationships: "phone is a sound emitter" and "phone is a communication device."

In order to construct objects of this class, Phone must implement the abstract functions of both of the interfaces:

class Phone : SoundEmitter, CommunicationDevice {
    string emitSound() {           // for SoundEmitter
        return "rrring";
    }

    void talk(string message) {    // for CommunicationDevice
        // ... put the message on the line ...
    }

    string listen() {              // for CommunicationDevice
        string soundOnTheLine;
        // ... get the message from the line ...
        return soundOnTheLine;
    }
}

A class can inherit from any number of interfaces as it makes sense according to the design of the program.

Inheriting from interface and class

Classes can still inherit from up to one class as well:

class Clock {
    // ... clock implementation ...
}

class AlarmClock : Clock, SoundEmitter {
    string emitSound() {
        return "beep";
    }
}

AlarmClock inherits the members of Clock. Additionally, it also provides the emitSound() function that the SoundEmitter interface requires.

Inheriting interface from interface

An interface that is inherited from another interface effectively increases the number of functions that the subclasses must implement:

interface MusicalInstrument : SoundEmitter {
    void adjustTuning();
}

According to the definition above, in order to be a MusicalInstrument, both the emitSound() function that SoundEmitter requires and the adjustTuning() function that MusicalInstrument requires must be implemented.

For example, if Violin inherits from MusicalInstrument instead of SoundEmitter, it must now also implement adjustTuning():

class Violin : MusicalInstrument {
    string emitSound() {     // for SoundEmitter
        return "♩♪♪";
    }

    void adjustTuning() {    // for MusicalInstrument
        // ... special tuning of the violin ...
    }
}
static member functions

I have delayed explaining static member functions until this chapter to keep the earlier chapters shorter. static member functions are available for structs, classes, and interfaces.

Regular member functions are always called on an object. The member variables that are referenced inside the member function are the members of a particular object:

struct Foo {
    int i;

    void modify(int value) {
        i = value;
    }
}

void main() {
    auto object0 = Foo();
    auto object1 = Foo();

    object0.modify(10);    // object0.i changes
    object1.modify(10);    // object1.i changes
}

The members can also be referenced by this:

    void modify(int value) {
        this.i = value;    // equivalent of the previous one
    }

A static member function does not operate on an object; there is no object that the this keyword would refer to, so this is not valid inside a static function. For that reason, none of the regular member variables are available inside static member functions:

struct Foo {
    int i;

    static void commonFunction(int value) {
        i = value;         // ← compilation ERROR
        this.i = value;    // ← compilation ERROR
    }
}

static member functions can use only the static member variables.

Let's redesign the Point struct that we have seen earlier in the Structs chapter, this time with a static member function. In the following code, every Point object gets a unique id, which is determined by a static member function:

import std.stdio;

struct Point {
    size_t id;    // Object id
    int line;
    int column;

    // The id to be used for the next object
    static size_t nextId;

    this(int line, int column) {
        this.line = line;
        this.column = column;
        this.id = makeNewId();
    }

    static size_t makeNewId() {
        immutable newId = nextId;
        ++nextId;
        return newId;
    }
}

void main() {
    auto top = Point(7, 0);
    auto middle = Point(8, 0);
    auto bottom =  Point(9, 0);

    writeln(top.id);
    writeln(middle.id);
    writeln(bottom.id);
}

The static makeNewId() function can use the common variable nextId. As a result, every object gets a unique id:

0
1
2

Although the example above contains a struct, static member functions are available for classes and interfaces as well.

final member functions

I have delayed explaining final member functions until this chapter to keep the earlier chapters shorter. final member functions are relevant only for classes and interfaces because structs do not support inheritance.

final specifies that a member function cannot be redefined by a subclass. In a sense, the implementation that this class or interface provides is the final implementation of that function. An example of a case where this feature is useful is where the general steps of an algorithm are defined by an interface and the finer details are left to subclasses.

Let's see an example of this with a Game interface. The general steps of playing a game is being determined by the play() function of the following interface:

interface Game {
    final void play() {
        string name = gameName();
        writefln("Starting %s", name);

        introducePlayers();
        prepare();
        begin();
        end();

        writefln("Ending %s", name);
    }

    string gameName();
    void introducePlayers();
    void prepare();
    void begin();
    void end();
}

It is not possible for subclasses to modify the definition of the play() member function. The subclasses can (and must) provide the definitions of the five abstract member functions that are declared by the interface. By doing so, the subclasses complete the missing steps of the algorithm:

import std.stdio;
import std.string;
import std.random;
import std.conv;

class DiceSummingGame : Game {
    string player;
    size_t count;
    size_t sum;

    string gameName() {
        return "Dice Summing Game";
    }

    void introducePlayers() {
        write("What is your name? ");
        player = strip(readln());
    }

    void prepare() {
        write("How many times to throw the dice? ");
        readf(" %s", &count);
        sum = 0;
    }

    void begin() {
        foreach (i; 0 .. count) {
            immutable dice = uniform(1, 7);
            writefln("%s: %s", i, dice);
            sum += dice;
        }
    }

    void end() {
        writefln("Player: %s, Dice sum: %s, Average: %s",
                 player, sum, to!double(sum) / count);
    }
}

void useGame(Game game) {
    game.play();
}

void main() {
    useGame(new DiceSummingGame());
}

Although the example above contains an interface, final member functions are available for classes as well.

How to use

interface is a commonly used feature. There is one or more interface at the top of almost every class hierarchy. A kind of hierarchy that is commonly encountered in programs involves a single interface and a number of classes that implement that interface:

               MusicalInstrument
                 (interface)
               /    |     \     \
          Violin  Guitar  Flute  ...

Although there are more complicated hierarchies in practice, the simple hierarchy above solves many problems.

It is also common to move common implementation details of class hierarchies to intermediate classes. The subclasses inherit from these intermediate classes. The StringInstrument and WindInstrument classes below can contain the common members of their respective subclasses:

               MusicalInstrument
                 (interface)
                 /         \
   StringInstrument       WindInstrument
     /    |     \         /      |     \
Violin  Viola    ...   Flute  Clarinet  ...

The subclasses would implement their respective special definitions of member functions.

Abstraction

Interfaces help make parts of programs independent from each other. This is called abstraction. For example, a program that deals with musical instruments can be written primarily by using the MusicalInstrument interface, without ever specifying the actual types of the musical instruments.

A Musician class can contain a MusicalInstrument without ever knowing the actual type of the instrument:

class Musician {
    MusicalInstrument instrument;
    // ...
}

Different types of musical instruments can be combined in a collection without regard to the actual types of these instruments:

    MusicalInstrument[] orchestraInstruments;

Most of the functions of the program can be written only by using this interface:

bool needsTuning(MusicalInstrument instrument) {
    bool result;
    // ...
    return result;
}

void playInTune(MusicalInstrument instrument) {
    if (needsTuning(instrument)) {
        instrument.adjustTuning();
    }

    writeln(instrument.emitSound());
}

Abstracting away parts of a program from each other allows making changes in one part of the program without needing to modify the other parts. When implementations of certain parts of the program are behind a particular interface, the code that uses only that interface does not get affected.

Example

The following program defines the SoundEmitter, MusicalInstrument, and CommunicationDevice interfaces:

import std.stdio;

/* This interface requires emitSound(). */
interface SoundEmitter {
    string emitSound();
}

/* This class needs to implement only emitSound(). */
class Bell : SoundEmitter {
    string emitSound() {
        return "ding";
    }
}

/* This interface additionally requires adjustTuning(). */
interface MusicalInstrument : SoundEmitter {
    void adjustTuning();
}

/* This class needs to implement both emitSound() and
 * adjustTuning(). */
class Violin : MusicalInstrument {
    string emitSound() {
        return "♩♪♪";
    }

    void adjustTuning() {
        // ... tuning of the violin ...
    }
}

/* This interface requires talk() and listen(). */
interface CommunicationDevice {
    void talk(string message);
    string listen();
}

/* This class needs to implement emitSound(), talk(), and
 * listen(). */
class Phone : SoundEmitter, CommunicationDevice {
    string emitSound() {
        return "rrring";
    }

    void talk(string message) {
        // ... put the message on the line ...
    }

    string listen() {
        string soundOnTheLine;
        // ... get the message from the line ...
        return soundOnTheLine;
    }
}

class Clock {
    // ... the implementation of Clock ...
}

/* This class needs to implement only emitSound(). */
class AlarmClock : Clock, SoundEmitter {
    string emitSound() {
        return "beep";
    }

    // ... the implementation of AlarmClock ...
}

void main() {
    SoundEmitter[] devices;

    devices ~= new Bell;
    devices ~= new Violin;
    devices ~= new Phone;
    devices ~= new AlarmClock;

    foreach (device; devices) {
        writeln(device.emitSound());
    }
}

Because devices is a SoundEmitter slice, it can contain objects of any type that inherits from SoundEmitter (i.e. types that have an "is a" relationship with SoundEmitter). As a result, the output of the program consists of different sounds that are emitted by the different types of objects:

ding
♩♪♪
rrring
beep
Summary