18 February 2015

Embedding is beneficial

...whereas an explicit interface keyword is harmful

This is my own addendum to Uncle Bob's recent post on the interface keyword being a harmful keyword in Java. He references C# several times because it's like a sister-language to Java. There's a newer kid on the block that solves the problem rather elegantly...


So now what?

Well, try this on for size:

type Subject struct {
	observers []Observer
}

func (this *Subject) register(o Observer) {
	this.observers = append(this.observers, o)
}

func (this *Subject) notify() {
	for _, o := range this.observers {
		o.update()
	}
}

type MyWidget struct {
	/* ... */
}

type MyObservableWidget struct {
	*MyWidget
	*Subject
}

What is going on there?

Well, suppose you could define a class/struct with useful fields and methods, then allow other structs to borrow that data and functionality. It's not really inheritence but it feels like it. We'll call the technique embedding a struct.

That's really clean--what language is that?

Go from Google, with is also more flexible with interfaces in general, favoring implicit implementation to an explicit keyword sprinkled everywhere. Sort of like duck-typing in Python but without the dynamic type system.

Cool, I'll check it out!