Skip to the page
Start here / Habits that don't carry over

Start here01

The language02

Programs and the world03

Kiln04

01 Start here / 03

Habits that don't carry over

What code often does elsewhere, and what Hematite does instead: worth a read whatever you wrote before.

Everyone arrives with habits from the code they've written before. This page collects the ones that would be mistakes in Hematite, grouped by topic, each with what Hematite does instead. A habit that many languages share is listed once.

Each section says in a few lines how Hematite works there, shows one habit side by side with what to write instead, and lists the rest.

Lines and names

Hematite code has one statement on each line, and every block ends with end. Indentation is layout, which hem fmt keeps right; it never changes what code means. Names are plain ASCII, and their case means nothing. More in the basics.

Not this

Indentation ends a block.

Write this

end ends a block. Indentation is layout, which hem fmt keeps right.

HabitIn Hematite
; separates statementsNot allowed. One statement per line.
{ and } around blocksend closes a block.
=begin / =end block commentsNot allowed. Use # on every line.
A line starting with . or + continues the previous lineNot allowed. End the previous line with the operator instead.
Names may contain any Unicode (café)ASCII only. café is an error.
Uppercase names are constantsCase means nothing. const makes a variable unchangeable; static makes a value the file's methods and other files can use.

Numbers and arithmetic

Ints are 64-bit, and / always gives a Float, so you round when you want a whole number. A number that would overflow, or a division by zero, is an error rather than a surprising value. See values and numbers.

Not this

7 / 2 is 3 (Int division).

Write this

7 / 2 is 3.5. / always gives a Float; the whole-number division is 7.quotient(2), which is 3.

HabitIn Hematite
Integers grow without limit64-bit. Too-large literals and arithmetic overflow are errors.
a // b (whole-number division)a.quotient(b).
1.0 / 0 is InfinityError: division by zero.
a ** bNot available.
x += 1x = x + 1. There are no compound assignments.
+x (unary plus)Not allowed. Write x.
0o17, 0x1F, 017 (octal)Not supported. 017 is just 17.
1e20.to_s is "1.0e+20"Prints 1e20.
x.round(2) with half-to-even or binary surprisesx.round(2) rounds the number as it prints; halves go away from zero.

Printing

print takes exactly one value on every call, and prints it as it is. To print several values on one line, build a string. See printing.

Not this

print(a, b), an error

Write this

print("#{a} #{b}"). print takes exactly one value.

HabitIn Hematite
puts xprint(x).
println!("{}", x)print(x), or print("#{x}").
puts nil prints an empty linePrints nil.
puts alone prints an empty lineError: print takes exactly 1 argument.
puts a, b prints each on its own lineError. Use one print per value.

Variables

Every variable is declared, with const if it never changes and var if it does, and its type is fixed by its first value. A variable lives only in the block that declares it, and assigning is a statement of its own. See variables.

Not this

x = 1 creates a variable.

Write this

Declare it: const x = 1 or var x = 1. x = 1 only changes an existing var.

HabitIn Hematite
let x = 1var x = 1; const when it never changes.
let mut x = 1var x = 1.
val x = 1const x = 1.
x := 1const x = 1, or var x = 1 if it changes.
x = y = 0One assignment per line.
1 + x = 2, (x = 1), foo(x = 1) assign inside an expressionError. Assign on its own line first.
A variable can hold any type over timeIts type is fixed by its first value. var n = 1 then n = 1.5 is an error.
Variables assigned in an if exist after itVariables live only in their block. Declare before the if.
An inner variable may reuse an outer nameError: a name can't be declared while another variable with that name is visible.

Values that might be nil

There is one "nothing", nil, and only a type that says so (Int?, User?) can hold it. There are no shortcuts around a nil: you check with if x != nil, and the checker sees the check, so the code after it can use the value. See nil and optional types.

Not this

x?.y, x ?? y, x ?: y, x!!

Write this

Not available. Check if x != nil first; the checker sees the check.

HabitIn Hematite
null and undefinedOnly nil.
None, True, Falsenil, true, false.
let user: User | null = nullvar user: User? = nil
Option<T>T?, checked with if x != nil.
user!.name, as castsNot available. Check if user != nil first; the checker sees the check.

Calls and methods

Every call has parentheses, even with no arguments, because parentheses are what say a method runs: without them, a name is a value. Every argument after the first is named, every parameter has a type, and a method gives its result with return. See calls and methods.

Not this

transfer(50, savings, checking)

Write this

Every argument after the first is named: transfer(50.0, from: savings, to: checking).

HabitIn Hematite
add 1, 2 (a call without parentheses)Error. Write add(1, 2).
name.upcase, account.total (calls without arguments)Error. Write name.upcase(); without parentheses, a name is a value, like a field.
foo (1) (space before the parenthesis)Error. Write foo(1).
foo -1 / x -1 (guessed from spacing)Error. Write foo(-1) or x - 1.
def add(a, b)Every parameter needs a type: def add(a: Int, b: Int): Int.
function add(a, b), (a, b) => a + bdef add(a: Int, b: Int): Int. Blocks only go to built-in methods.
def greet without parenthesesdef greet().
def total(self):def total(): Int. self isn't a parameter; it's there in every method.
The last expression is returned automaticallyWrite return value. A method with a return type must return on every path.
Methods can change their parametersParameters are constants. Copy into a var to change.
def greet(name, loud = false), keyword argumentsdef greet(name: String, loud: Boolean = false), called as greet("Ada") or greet("Ada", loud: true).
Overloaded methodsOne method per name; a default value covers the optional parts.
*args, **optionsNot available yet.
Several return valuesReturn a record.

Conditions and choices

A condition must be true or false: nothing counts as true by itself. Logic is spelt and, or and not, every if block takes its own lines, and a one-line choice is a value. See conditions and loops.

Not this

Everything except nil and false is truthy: if user.

Write this

Conditions must be true or false. if 0, if nil, if user are errors; write if user != nil.

HabitIn Hematite
!x, &&, ||Use not x, and, or. They bind like !, && and || do.
and/or with unusually low precedenceand/or bind like &&/||: x = a or b assigns a or b.
AND, OR, NOT, &&, ||, !and, or, not, in lowercase only: any other spelling is an error.
1 < x < 3 fails at runtime (true < 3)Syntax error: comparisons can't be chained.
===, and == that converts== only, between values of the same type: comparing an Int with a String is an error.
<=>, ===, =~Not available.
elsifelse if, on one line.
elifelse if.
unless xUse if not x.
until xUse while not x.
print(x) if ok (modifier form)Use a full if ... end block.
if x then y end on one lineOnly as a value: v = if x then a else b. Blocks use separate lines.
ok ? a : bif ok then a else b. Never nested.
x if ok else yif ok then x else y.
x = if ok ... end (multi-line if gives a value)Use the one-line if ... then ... else, or assign inside the branches of an if block.

Choosing by value

A fixed set of states is an enum, and when chooses between its values. when works only for enums, lists every value, and has no else, so adding a value shows you every place that has to handle it. For other values, use if and else if. See choosing by value.

HabitIn Hematite
Symbols like :draft for a fixed set of statesAn enum: enum Status with draft on its own line, used as Status.draft.
case status / when :draft / elsewhen status / is Status.draft / end, only for enums. Every value must be listed; there is no else. For other values, use if and else if.
switchwhen, for enums; if and else if for anything else.
matchwhen, for enums, listing every value; if and else if for anything else.
when with elsewhen is only for enums, lists every value, and has no else.

Loops and blocks

There are two ways to repeat: while, and each with a block. A block is written do (x) ... end, gives its value with return, and goes to a method that runs it; it isn't a value you can keep. See blocks.

Not this

for item in items:

Write this

items.each do (item) ... end.

HabitIn Hematite
for i in range(n):while, with a counter: var i = 0, then i = i + 1 in the loop.
for i := 0; i < n; i++while i < n, with i = i + 1. There's no ++.
items.forEach((item) => ...)items.each do (item) ... end.
items.each { |x| ... }, do |x| ... enditems.each do (x) ... end. No pipes, no braces.
The block's last line is its valuereturn value. In blocks, return ends just the block.
each_with_indexdo (item, index)
select, detect, any?, all?filter, find, any, all
items.map(&:name), reduce, injectNot available. sum, min, max, average and tally take a block; for anything else, use each and a var.
sort_by, sort { |a, b| ... }sort do (x) ... end, the block giving what to sort by.
take(n), drop(n)limit(n), skip(n).
group_by, uniqgroup do (x) ... end, the block giving each item's key; unique().
next (skip to the next pass)continue.
break value, next valuePlain break and continue, only in while and each.
lambda x: x * 2Blocks, given to the built-in methods that take them: items.map do (x): Int ... end.
def each(&block), block.call(x), keeping a blockA block isn't a value. A method says it takes one after its signature, def each_item() do (Int), and runs it with yield(x). It can't keep it.

Strings and conversions

Strings use double quotes, and #{} is the way to put a value into one, so text never joins a number by accident. Conversions are written out: String(n), Int(x), Float(s). See strings and conversions.

Not this

"age: " + 36 giving "age: 36"

Write this

"age: #{36}". Joining a string and a number with + is an error.

HabitIn Hematite
'single quoted' stringsDouble quotes only. Interpolation always works.
f"Hi {name}""Hi #{name}".
`Hi ${name}`"Hi #{name}".
"Hi $name""Hi #{name}".
Heredocs, %q(), '''A text block: """ ends its line, the closing """ starts one.
"#{nil}" is ""Error. Only values that can't be nil go into a string.
"a" * 3, "a" < "b"Not available yet.
len(items), len(text)items.length, text.length.
items.empty?, text.empty?items.length == 0
text.strip, text.include?("x"), items.include?(x)text.trim(), text.contains("x"), items.contains(x)
text[2..5], text.gsub("a", "b"), text.index("x"), text.charstext.slice(from: 2, to: 6), text.replace("a", by: "b"), text.index_of("x"), text.characters
text.start_with?("x"), text.end_with?("x")text.contains("x", at: Placement.start), at: Placement.finish
n.to_s, x.to_i, s.to_fString(n), Int(x), Float(s). Int(2.5) is an error: round first.

Arrays and hashes

An array or a hash holds one type, is read and written through its methods, and is a value: assigning it or passing it makes an independent copy. Reading past the end of an array is an error, never a quiet nil; a hash's get says it may be nil in its type, and the checker makes sure you check. See arrays and hashes.

Not this

ages["Ada"], ages["Bob"] = 40

Write this

ages.get("Ada"), ages.set("Bob", to: 40)

HabitIn Hematite
[1, "two", nil] (mixed arrays)One type per array. nil only in arrays typed like [Int?].
items[10] past the end gives nilError.
items[-1] is the last elementError. Use items[items.length - 1].
items << 4items.push(4)
items.size, items.countitems.length
b = a shares the array; changing b changes ab is an independent copy.
A method can change an array passed to itParameters can't be changed. Copy into a var, then return the result.
{"Ada" => 36}, {name: "Ada"} (symbol keys){"Ada": 36}. Keys are written-out strings or numbers. There are no symbols.
{name: 36} meaning the key "name"Error: write {"name": 36}.
dict["key"]ages.get("key"), ages.set("key", to: 1).
ages.fetch, ages.key?, ages.deleteages.get (gives nil when missing), ages.has, ages.remove
ages.fetch("Bob", 0)ages.get("Bob", fallback: 0)
Hash.new(0) (default values)Not available. Check with .has first.

Classes and objects

A class declares its fields at the top, with types, and its methods inside it. Objects are values, like arrays and hashes. Classes share fields and methods through traits: there is no inheritance, on purpose. See classes and records and traits.

Not this

@balance

Write this

self.balance

HabitIn Hematite
Fields appear when first assigned in initializeFields are declared at the top of the class, with types.
def initialize(...)new Account(owner: "Ada") sets the readable and writable fields by name.
Account.new(...)new Account(...)
attr_reader, attr_accessorreadable var, writable var
Calling an own method bare: totalself.total() (or self.total without arguments)
impl blocksMethods are written inside the class.
b = a shares the objectb is an independent copy.
Borrowing and lifetimesNone to think about: arrays, hashes and objects are values, copied when assigned.
Inheritance (class Admin < User)Not available, on purpose. Share fields and methods with a trait.
include Trackable (modules, concerns)A trait: trait Trackable ... end, and with Trackable at the top of the class.
Interfaces, abstract classesA trait: trait Name, and with Name in the class.
data class, record typesrecord: fields only, always readable, never changed.

Failures

A method that can fail says so in its return type, with !, and fails with return failure("..."). Every call to it handles the failure: try passes it on, rescue deals with it there. Nothing passes through a method without it saying so. See failures.

Not this

throw and try/catch

Write this

: T!, return failure("..."), and try or rescue at every call.

HabitIn Hematite
raise and rescue: any call may raise, and exceptions pass silently through methods that don't mention themA method that can fail says so (: Int!), and every call to it handles the failure with try or rescue. There is no raise and no begin.
try: / except / raiseA method that can fail says so (: Int!) and fails with return failure("..."); callers use try or rescue.
Exceptions, checked or not: T! and return failure("..."); every call handles it.
if err != nil { return err }try call() passes a failure on.
Result<T, E> and ?T! and try.
async/await, promisesNot needed: a call that waits, like File.read(path, as: String) or Input.line(), gives its result when it's there.
JSON.parse(text)try JSON.decode(text, as: Type): the result is checked against the type.

Files

A file shares only what it marks with export, and only with the files that import it. Case means nothing here either: a capital letter doesn't export a name, export does. See imports and exports.

Not this

require runs a file, and its definitions are then visible everywhere.

Write this

import brings in only what a file exports, only into the file that imports it, and runs none of its code.