Tantawowa LLC

Tantawowa

Get some class!

If you’re a Roku developer, you know that writing code in the global namespace can quickly become a nightmare. Not only does this make it difficult to manage your code, but it can also lead to namespace collisions and other issues. That’s why it’s much better to use object-oriented programming and classes to write Roku apps.

The new Brighterscript language, which is a superset of BrightScript, makes it easy to write classes. With its class keyword support, you can create classes and use them to organize your code in a more logical and maintainable way.

Classes in Brighterscript
For example consider a Manager class, with a login, logout and purchase function.

class Manager
public function login(username as String, password as String)
' Implement login functionality here
end function

public function logout()
' Implement logout functionality here
end function

public function purchase(item as String, quantity as Integer)
' Implement purchase functionality here
end function
end class

You can then instantiate the class and call its methods like this:

manager = new Manager()
manager.login("testuser", "password123")
manager.purchase("item1", 1) 
manager.logout()

Classes in regular brs
But even if you’re not using Brighterscript, it’s still possible to write classes in regular BrightScript. This is done by adding functions to an associative array.

Here is an example of a createManager function that returns an associative array containing the class methods:
function createManager()
  return {
    login: manager_login,
    logout: manager_logout,
    purchase: manager_purchase
  }
end function
Here are template functions for the manager_login, manager_logout, and manager_purchase methods:
function manager_login(username as String, password as String)
  ' Implement login functionality here
end function

function manager_logout()
  ' Implement logout functionality here
end function

function manager_purchase(item as String, quantity as Integer)
  ' Implement purchase functionality here
end function

Using this approach, you can create classes in BrightScript without using the class keyword. You can then instantiate the class and call its methods like this:

manager = createManager()
manager.login("testuser", "password123")
manager.purchase("item1", 1)
manager.logout()

While this method is not as elegant as using the class keyword in Brighterscript, it has been used by many Roku developers for many years, and can help you embrace object-oriented programming on the platform.

Take home

In my opinion, using Brighterscript to write classes is the future of Roku programming. But if your company doesn’t support Brighterscript, using the associative array method is a great way to get some of the benefits of object-oriented programming on Roku. No matter what approach you take, using classes will make your code easier to reason about, easier to test, and more maintainable in the long run.