Skip to content

Instantly share code, notes, and snippets.

@PhilipWitte
Last active August 29, 2015 14:02
Show Gist options
  • Save PhilipWitte/b1316b22d69b47bcf593 to your computer and use it in GitHub Desktop.
Save PhilipWitte/b1316b22d69b47bcf593 to your computer and use it in GitHub Desktop.
trait IActor:
method update*
trait IVisual:
method render* {.optional.}
class Person of TObject is IActor IVisual:
var name: string
var age: uint
proc new(name:string, age:uint) {.init.} =
this.name = name
this.age = age
method update* =
this.age += 1
method render* =
echo "Hi, I'm ", this.name, "."
echo "I am ", this.age, " years old."
# ---
var p = Person.new("Philip", 26)
var a: IActor = p
var v: IVisual = p
a.update()
v.render()
# OUPUT:
# ----------
# Hi, I'm Philip.
# I am 27 years old.
@PhilipWitte
Copy link
Author

@ Jehan_

Hey, you around? Wanted to talk about OOP stuff now. Concerning multi-interfaces vs parametric polymorphism, I wrote a simple example of OOP Nimrod code (using some pseudo macros I'm currently designing) which is very trivial.

It's just one class, two interfaces (traits). Note that I'm using 'method' to denote dynamic dispatch, but these procedures will actually convert to custom dispatch trees (not Nimrod's built-in method dispatch, which only supports single inheritance). My question to you, is what design practice you consider better practice than this, and why?

I could pass p to a generic proc which duck-types it against IAction/IVisual and returns a structure with (which is, I assume, akin to what you mean by 'parametric polymorphism')... but that's (one way to achieve) pretty exactly what is going on here. Except that I'm building it into the trait object which has the benefits of enforcing behavior at class declaration, isolating potential references the class can be used from (helpful for sanity on large codebases with many devs), and potentially optimizing the code (because dispatch trees are theoretically inlineable and use less memory than procvar lists).

So i'm interested to hear your thoughts on better design approaches to this simple example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment