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

Proposal: Add class type #1382

Open
addison-adler opened this issue Dec 22, 2024 · 1 comment
Open

Proposal: Add class type #1382

addison-adler opened this issue Dec 22, 2024 · 1 comment

Comments

@addison-adler
Copy link
Contributor

addison-adler commented Dec 22, 2024

The Problem

There's currently no built-in way to distinguish a brighterscript class from other classes or plain assocarrays. We can manually add our own "type" property, but have to do that for every class we ever create.. and on teams with multiple members, that's also left to memory and easy to forget

Proposal

This is a similar problem that JavaScript prototypes have (which are very similar to brighterscript classes). A potential pattern that we could mirror was added in ES6:

JS ES6 solved this by adding the constructor.name property

For Brighterscript, the simplest way to add this might look like:
(transpiled)

function __exampleClass_builder()
  instance = {}
  instance._isClass = true
  instance._name = "exampleClass"
  return instance
end function

function exampleClass(args)
  instance = __exampleClass_builder()
  instance.new(args)
  return instance
end function

Value-Add

This opens up room for developers to use simple utils like [the following] to differentiate classes from eachother and other objects

function isClass (value)
  return isAssocArray(value) and (true = value._isClass)
end function

function isClassOf (value, classType)
  return isClass(value) and (value._name <> invalid) and (value._name = classType)
end function

Closing Remarks

Open to discussion/suggestions on what this should look like for Brighterscript. Once there's consensus, I don't mind doing the PR

@addison-adler
Copy link
Contributor Author

addison-adler commented Dec 22, 2024

Addendum:

Following ES6's pattern, since the transpiled function is a namespaced func, we could do...

function __exampleClass_builder()
  instance = {}
  instance.constructor = exampleClass
  return instance
end function

function exampleClass(args)
  instance = __exampleClass_builder()
  instance.new(args)
  return instance
end function

This mirrors the ES6 solution more closely and still empowers you to check "is this a class?" and "is this a class of specific type?"

(answered by "does it have a constructor property?" and "does the constructor property match the function call to create this 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