Hacker News new | ask | show | jobs
by jmpeax 4398 days ago
One of the best type features of Go is the lack of need to do something like this: "@implements(IEatable)". If a class implements all of the methods of the interface, then it automatically implements that interface. Yuppy seems like a step backwards in OO in this regard.
2 comments

Is it possible to indicate, in an interface, that it's not a structural type? Ie, that classes need to specifically indicate they implement it to be considered it's type?

For example, the HtmlString interface could require only "toString" as a method, but not everything that has that method should be considered that type.

The idea would be, in this case, to create a method called "toHtmlString". The name "toString" suggests a generic String is created for the object, but HtmlString represents a specially formatted String.

Rather than having a class implement HtmlString as a way to specify that its "toString" method works differently to the usual or expected way for a method of that signature, you can instead write a "toHtmlString" which is more clear. Reading code as "myObject.toString()" vs "myObject.toHtmlString()" is better than having to check the class signature for a special contract pertaining to general-looking method names.

I would definitely prefer jmpeax's answer.

Although, there was a question/discussion similar to this here: https://www.youtube.com/watch?v=u-kkf76TDHE#t=2584

The gist was that, if the interface and the structs that are supposed to satisfy that interface belong to the same package, and then you want to prevent any outsider from implementing that interface, you can actually include an unexported method:

    type HtmlStringer interface {
        ToString() string
        isHtmlStringer()
    }
Since it is unexported, no outsider struct can actually satisfy this interface anymore.
Thankfully in Python this isn't required either. Implement all of the methods of an interface and duck typing will take care of the rest for you...