Version: v0.7.1 - Beta.  We welcome contributors & feedback.

Getters & Setters

Getters and setters are methods that are used to access an object’s data.


Normally, any public field can be read from outside the object.

However, in future iterations of your code, you might need to change how this value is calculated. (e.g. Converting units or changing the format.)

In THT, you can make an update like this without having to change the outside code, by defining a getter method that follows the getFieldName naming convention.

When a matching public field is read from outside the object, the result of the getter method will be returned instead.

class User {

    public fields {
        userId: 0,

    // Getter for 'userId'
    fn getUserId {
        // Add a prefix
        return 'id_' ~ @.userId

// Another file

$user = User({ userId: 123 })

//= 'id_123'


In THT, all public fields are read-only, so if you want to allow code outside the object to change a field, you must create a method to do so.

There are no built-in shortcuts for creating setter methods.


In this example, takeDamage is a setter method that modifies the health field.

class Character {

    fields {
        health: 33,

    // Changing a private field via a method
    public fn takeDamage($damage) { -= $damage
        print('Health: ' ~

// Another file

$player = Character()

//= 'Health: 13'

Tip: How to Create Good Setters

Do your best to avoid creating methods that simply change a field. (e.g. “setUserId”)

Instead think of your methods as an interface that lets outside callers work with the higher-level meaning (i.e. semantics) of the object.

By adding meaningful interfaces to your objects, your code will be less tightly coupled, or less tangled together.


// ✕ NO - tight coupling      // ✓ YES - meaningful

$car.setSpeed()         -->   $car.accelerate()
$car.setDirection()     -->   $car.turn()
$computer.setPower()    -->   $computer.turnOn()
$user.setGroup()        -->   $user.joinGroup()
$account.setBalance()   -->   $account.depositMoney()
$monster.setHealth()    -->   $monster.takeDamage()
$post.setIsPublished()  -->   $post.publish()

Sidebar: Data Hiding 

The technique of encapsulation (or “data hiding”) is central to software design — and it is especially important in object-oriented programming (OOP).

An object is considered encapsulated when there is a clear boundary protecting its inner data from the outside world.

This might seem inconvenient at first, but it creates a major benefit: psychological “chunking”.

When an object is cleanly separated like this, there is less ambiguity, and less code you need to keep in your limited (human) memory while you are working on it.

It also leads to a more flexible codebase because objects can easily be modified or replaced without affecting the surrounding code (aka “loose coupling”).