Classes
Why This Matters
Use a class when data and behavior belong together and you want one clear API around that state. For beginners: a class is a custom type that stores fields and exposes methods.
Mental Model
classdefines a type- fields store data (
name: Type) muton a field means that field can change- methods are functions attached to the class
- constructor sets initial valid state
Minimal Runnable Example
import std.io.*;
class Counter {
mut value: Integer;
constructor(start: Integer) {
this.value = start;
}
function increment(): None {
this.value += 1;
return None;
}
function current(): Integer {
return this.value;
}
}
function main(): None {
mut c: Counter = Counter(10);
c.increment();
println("counter={c.current()}");
return None;
}
Field Mutability (mut) vs Immutable Fields
class User {
id: Integer;
mut points: Integer;
constructor(id: Integer) {
this.id = id;
this.points = 0;
}
}
idcannot be reassigned after constructionpointscan be updated in methods
Practical rule:
- keep fields immutable unless you have a clear state transition reason
- expose state changes through methods, not ad-hoc writes everywhere
Visibility and Inheritance
Class fields/methods can use visibility modifiers (public, protected, private) and classes can extend base classes with extends.
For practical examples:
Destructors
Arden classes support destructor() for cleanup-oriented logic on object teardown.
Practical rules:
- keep destructor logic minimal and deterministic
- avoid complex control flow in destructors
- class can define at most one destructor
Constructor Guidance
Constructors are where you enforce invariants early. If a value must never be negative/empty/invalid, validate before storing.
Compiler constraints for class lifecycle declarations:
- at most one
constructorper class - at most one
destructorper class - visibility modifiers are not allowed on constructors/destructors
- attributes are not allowed on constructors/destructors
API Boundary Rule
If external code should not directly mutate internals, keep fields non-public and
offer explicit methods (deposit, rename, setStatus) that validate changes.
Common Mistakes
- forgetting
muton fields that methods change - exposing fields and mutating everywhere instead of centralizing mutation in methods
- using classes for data that has no behavior (module + plain values may be cleaner)
When To Use What
- class: state + methods travel together
- enum: finite known states/variants
- module: namespace/grouping of functions
Related
- Interfaces
- Language Edges
- Ownership
- Example:
05_classes