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

Initializing protocol fields #35

Open
benash opened this issue Dec 21, 2018 · 1 comment
Open

Initializing protocol fields #35

benash opened this issue Dec 21, 2018 · 1 comment

Comments

@benash
Copy link

benash commented Dec 21, 2018

Hi, thanks for your work on this interesting proposal. Would be possible to initialize a protocol field by accessing this, or would that need to be a method? E.g.:

protocol Pageable {
  pageSize
  items

  getFirstPage() {
    return this[Pageable.items].slice(0, this[Pageable.pageSize])
  }
}

class GroceryList {
  constructor(items) {
    this.items = items
  }
  implements protocol Pageable {
    pageSize = 2
    items = this.items                // <-- Would this be legal?
    get items() { return this.items } // <-- Or this?
    items() { return this.items }     // <-- Or would this be the only way to go?
  }
}
@mlanza
Copy link

mlanza commented May 5, 2023

Having implemented protocols in my own library I'll offer my perspective.

Protocols are contracts (or rather behaviors) applied to types so any object of a type automatically observes the contract. They're not applied to existing objects. You can create reified instances of a protocol, but that's a separate concern. I know it's all a matter of implementation/choice, but I implemented protocols as solely functions/methods (command or query), not properties, following after what Clojure did.

I would think rather your types implement the properties (and their defaults) apart from the protocol and the protocol methods simply make use of those properties. The properties, if absolutely necessary, would rather become part of an interface (see TypeScript's). And, for what it's worth, although similar, protocols and interfaces are not the same thing.

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

2 participants