Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Traits based approach #34

Open
iddan opened this issue Sep 14, 2018 · 0 comments
Open

Traits based approach #34

iddan opened this issue Sep 14, 2018 · 0 comments

Comments

@iddan
Copy link

iddan commented Sep 14, 2018

I'd like to suggest a different approach for this proposal: instead of a class to implement protocols on declaration it will implement different protocols in a different statement for each protocol. This approach is known as Traits and can be seen in Scala, Rust, and other languages.

Traits enable better separation of concerns, composability, and are a static single solution for associating a protocol to a class, already declared (like Object) or not.

References:

Traits: Composable Units of Behavior | Nathanael Schärli, Stéphane Ducasse, Oscar Nierstrasz
and Andrew Black

Syntax

protocol ProtocolName {
  // declare a symbol which must be implemented
  requiredMethodName;

  // and some methods that are provided by implementing this protocol
  providedMethodName(...parameters) {
    methodBody;
  }
}

class ClassName {
}

implement ProtocolName for ClassName {
    [ProtocolName.requiredMethodName]() {
        // this is the implementation for this class
    }
}

Example

protocol ToString {
  tag;

  toString() {
    return `[object ${this[ToString.tag]}]`;
  }
}

implement ToString for Object {
  [ToString.tag] = "Object";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant