Lesson 07 of 16

Object-Oriented Programming

class, model, this, methods

download this lesson (.md) ↓ all lessons

7. Object-Oriented Programming

STencil has two OOP styles: class (explicit this.) and model (bare fields).

class — with this

class Account {
    func init(owner, balance) {   // init = constructor
        this.owner = owner;
        this.balance = balance;
    }
    func deposit(amount) {
        this.balance = this.balance + amount;
    }
    func withdraw(amount) {
        if (amount > this.balance) {
            print("Insufficient funds");
            return null;
        }
        this.balance = this.balance - amount;
    }
    func report() {
        return this.owner + ": " + this.balance;
    }
}

let a = Account("Ember", 100);   // create (also: new Account("Ember", 100))
a.deposit(50);
a.withdraw(30);
print(a.report());     // Ember: 120
print(a.balance);      // 120   (read a field directly)
  • init is the constructor, run automatically on creation.
  • this.field reads/writes the object's fields.
  • obj.method(args) calls a method; obj.field reads a field.
  • Create with ClassName(args) or new ClassName(args).

model — bare fields

A model declares fields with optional defaults and lets methods use field names without this.:

model Car {
    marka: string
    mut hiz: int = 0
    init(m) {
        marka = m
    }
    hizlan(x) {
        hiz = hiz + x
        print(marka + " speed: " + hiz)
    }
}

let c = Car("Toyota");
c.hizlan(20);   // Toyota speed: 20
c.hizlan(30);   // Toyota speed: 50

Which to use?

  • class is explicit and familiar (like most languages).
  • model is shorter for data-heavy objects.

Both create objects you access with .field and .method().

Next: Stencils — the signature feature