Alternatives to OOP in D
Kapendev
alexandroskapretsos at gmail.com
Mon Sep 1 15:44:19 UTC 2025
On Monday, 1 September 2025 at 13:58:23 UTC, Brother Bill wrote:
> I have heard that there are better or at least alternative ways
> to have encapsulation, polymorphism and inheritance outside of
> OOP.
>
> With OOP in D, we have full support for Single Inheritance,
> including for Design by Contract (excluding 'old'). D also
> supports multiple Interfaces.
>
> What would be the alternatives and why would they be better?
> I assume the alternatives would have
> 1. Better performance
> 2. Simpler syntax
> 3. Easier to read, write and maintain
>
> If possible, please provide links to documentation or examples.
I sometimes use single-level inheritance with structs when making
games:
```d
import std.stdio;
struct Base {
int hp; // Everyone will have this.
void draw() { writeln("Debug stuff."); }
}
// Will use `Base.draw` by default.
struct Door {
Base base;
alias base this;
}
// Will use the custom draw function.
struct Player {
Base base;
alias base this;
int[] items;
void draw() { writeln("Player stuff."); }
}
void foo(Base* base) => base.draw();
void main() {
Door door;
Player player;;
player.draw();
foo(cast(Base*) &player);
door.draw();
foo(cast(Base*) &door);
}
```
It's nice because you can have one (sometimes static) array of
game entities. Needs the first member to be Base of course.
[Alias This](https://dlang.org/spec/struct.html#alias-this)
More information about the Digitalmars-d-learn
mailing list