bolt icon indicating copy to clipboard operation
bolt copied to clipboard

Add methods to types

Open matjaz opened this issue 10 years ago • 6 comments

For easier maintenance and encapsulate add custom methods.

type CustomMethods {
  validate() {
    return this.magic(this.value);
  }

  magic(question) {
    return question == this.answer();
  }

  answer() {
    return 42;
  }

}

matjaz avatar Aug 28 '15 11:08 matjaz

Do you envision this being used external to the type definition? E.g.

path /my/path {
  validate() { return this instanceof CustomMethods && this.magic() == 42; }
}

Since "this" is not strongly types, it would be difficult to statically analyze what method you were calling.

However, I've been considering replacing the "instanceof" operator with:

path /my/path is CustomMethods {
  validate() { return this.magic() == 42; }
}

So an exposed "method" on a type would be statically determined.

mckoss avatar Aug 28 '15 11:08 mckoss

For purely local, "helper functions" an alternative is supporting scoped functions within a type or path:

type CustomMethods {
  validate() {
    return magic(this.value);
  }

  function magic(question) {
    return question == answer();
  }

  function answer() {
    return 42;
  }
}

mckoss avatar Aug 28 '15 11:08 mckoss

I like "is" instead of instanceof. Just don't forget about inheritance, so also ancestor methods can be invoked.

Calling answer() without this would have different behaviour than in TypeScript. I would prefer sticking to TypeScript syntax. For example what if you have answer method and global function.

matjaz avatar Aug 28 '15 13:08 matjaz

Custom methods seem consistent.

tomlarkworthy avatar Aug 28 '15 17:08 tomlarkworthy

Yes, the behavior of "is" with respect to validate() rules is to AND all the validate() expressions of the extended types.

mckoss avatar Aug 28 '15 17:08 mckoss

I'm a fan of methods on types so long as validate methods within types only refer to global or type methods that don't access persistent data. This should be enforced at compile time. The read() and write() methods are the most appropriate place for data accesses.

TristonianJones avatar Sep 01 '15 04:09 TristonianJones