Style guide

Code is read far more often than it is written. This guide keeps Agentica code simple and easy to read, in the spirit of the Ruby and Elixir style guides. When a rule gets in the way of clear code, clear code wins. Restyle only the code you touch.

Some rules are enforced: the program does not compile when it breaks them. Their examples are marked “Does not compile” and show the error code.

Layout #

Indent with two spaces. No tabs, no trailing spaces, and one newline at the end of the file.

Keep lines at 119 characters or less, comments included. Wrap a long call or list with one item per line and a trailing comma:

# good
struct User
  name: String
  age: Int
  email: String
end

def main() -> Void
  user = User(
    name: "Ana",
    age: 25,
    email: "ana@example.com",
  )
  puts(user.name)
end

Wrap a long expression in parentheses. Never continue an expression on a bare line:

# good
def label(first: String, last: String, title: String) -> String
  return (
    "#{title} #{first} #{last}, " +
    "member of the board since 2001"
  )
end

def main() -> Void
  puts(label("Ana", "Diaz", "Dr."))
end

Put spaces around operators and after commas, but not around .. and ... or inside brackets or parentheses: total(a, b) + 1, [1, 2, 3], 0..9.

Separate top-level declarations with one blank line. Do not put blank lines right after def or before end, or two blank lines in a row.

# bad
def one() -> Int
  return 1
end
def main() -> Void
  puts(one())
end
Does not compile
error[PARSE-MISSING-BLANK-LINE]

Put a blank line after the end of a block before the next statement. The examples on this site follow it, and blank_line_after_end = true under [style] in agentica.toml makes agentica check enforce it (see the modules reference).

Naming #

WhatStyleExample
functions, variables, fields, filessnake_caseread_line, max_len, http_client.agc
structs, enums, variantsCamelCaseUser, Shape.Circle
constantsUPPER_SNAKE_CASEMAX_TRIES

The first letter is enforced, and so is a constant in capitals:

# bad
Limit = 10

def main() -> Void
  puts(Limit)
end
Does not compile
error[PARSE-CONSTANT-NAME]

A function that returns a Bool ends in ? and reads as a question. Do not use an is_ prefix:

# good
def blank?(text: String) -> Bool = text.length == 0

def main() -> Void
  puts(blank?(""))
end

A name that ends in ! stops the program instead of returning a Result. Give a function a ! only when it does that.

Name things by what they mean, not by their type: price, not int_value. Name a number that has a meaning, and use _ in big numbers:

# good
MAX_BYTES = 1_048_576

def too_big?(bytes: Int) -> Bool = bytes > MAX_BYTES

def main() -> Void
  puts(too_big?(2048))
end

Say it positively. Put the positive case first and do not pair a negated test with else:

# good
def describe(visible: Bool) -> String
  return "shown" if visible

  "hidden"
end

def main() -> Void
  puts(describe(true))
end

Files and docs #

A file has a fixed order: its doc and imports; the public part (constants, then structs, enums, type aliases, module blocks and extern blocks with a resource, then functions); a private line with a blank line before and after it; then the private part in the same order. Sort imports by path. A constant reads through the alias (Limits.LIMIT) like the rest; import it by name (import {LIMIT} from "limits") when it is used often, and a file may import one module both ways.

# bad
def main() -> Void
  puts("x")
end

struct Item
  name: String
end
Does not compile
error[CHECK-DECL-ORDER]

Keep one topic per file, and make public only the names that other files use.

Document as little as possible. Only public code gets a ## doc: a public function, struct or enum, saying what it returns or is, not how. A private function never gets ##; when it needs a note, use one # comment. A field or variant gets a note only when its name does not say enough. A # comment says why the code is the way it is, not what the next line does:

# bad
## This function loops over the prices and adds them up.
def total(prices: List[Int]) -> Int
  sum = 0
  # add each price to sum
  for price in prices
    sum += price
  end

  sum
end

def main() -> Void
  puts(total([250, 199]))
end
# good
## Returns the sum of the prices, in cents.
def total(prices: List[Int]) -> Int
  sum = 0
  for price in prices
    sum += price
  end

  sum
end

private

def main() -> Void
  puts(total([250, 199]))
end

Delete code instead of commenting it out.

Functions #

Give each function one job. If comments split it into parts, split it into functions.

Use four parameters or fewer. Put more in a struct. A function whose body is one value is a one-line def, def double(n: Int) -> Int = n * 2; agentica fmt writes it so. Return early on bad cases, so the main path stays flat:

# bad
def ship(weight: Int, width: Int, height: Int, depth: Int, rush: Bool) -> Int
  cost = 0
  if weight > 0
    if width > 0
      if rush
        cost = weight * 3
      else
        cost = weight * 2
      end
    end
  end

  cost
end

def main() -> Void
  puts(ship(2, 10, 10, 10, true))
end
# good
struct Parcel
  weight: Int
  width: Int
  height: Int
  depth: Int
  rush: Bool
end

def ship(parcel: Parcel) -> Int
  return 0 if parcel.weight <= 0 or parcel.width <= 0

  return parcel.weight * 3 if parcel.rush

  parcel.weight * 2
end

def main() -> Void
  puts(ship(Parcel(weight: 2, width: 10, height: 10, depth: 10, rush: true)))
end

A record with known fields is a struct, not a map:

# good
struct User
  name: String
end

def greet(user: User) -> String = "hello #{user.name}"

def main() -> Void
  puts(greet(User(name: "Ana")))
end

Use a for loop for a running total, and a method such as map to transform a list. A block cannot assign a variable from outside it:

# bad
def main() -> Void
  sum = 0
  [1, 2].each do |x| sum += x end
  puts(sum)
end
Does not compile
error[CHECK-CAPTURED-ASSIGNMENT]
# good
def main() -> Void
  sum = 0
  for x in [1, 2]
    sum += x
  end

  puts(sum)
  puts([1, 2].map do |x| x * 2 end)
end

Give a call a block only for a short body, one expression such as do |order| order.item end. A longer body, such as a route handler (|> Bond.get("/users/:id", &show_user)) or several statements, is a named function passed with &name:

# bad
struct Order
  item: String
  price: Int
  count: Int
end

def main() -> Void
  orders = [Order(item: "tea", price: 3, count: 2)]
  lines = orders.map do |order|
    total = order.price * order.count
    tax = total / 10
    "#{order.item}: #{total + tax}"
  end

  puts(lines)
end
# good
struct Order
  item: String
  price: Int
  count: Int
end

def line(order: Order) -> String
  total = order.price * order.count
  tax = total / 10
  "#{order.item}: #{total + tax}"
end

def main() -> Void
  orders = [Order(item: "tea", price: 3, count: 2)]
  puts(orders.map(&line))
  puts(orders.map do |order| order.item end)
end

Use a Bool as it is, with and, or and not, never compared with true or false:

# good
def allowed?(admin: Bool, banned: Bool) -> Bool = admin and not banned

def main() -> Void
  puts(allowed?(true, false))
end

if and case #

Use if for a yes-or-no question. Use case for an enum, a Result, or three or more branches on one value:

# bad
def size_name(n: Int) -> String
  if n == 0
    "empty"
  elsif n == 1
    "one"
  else
    "many"
  end
end

def main() -> Void
  puts(size_name(3))
end
# good
def size_name(n: Int) -> String
  case n
    0 -> "empty"
    1 -> "one"
    _ -> "many"
  end
end

def main() -> Void
  puts(size_name(3))
end

Name an enum for states instead of passing number codes:

# bad
def color_name(code: Int) -> String
  if code == 0
    return "red"
  elsif code == 1
    return "green"
  end

  "unknown"
end

def main() -> Void
  puts(color_name(1))
end
# good
enum Color
  Red
  Green
end

def color_name(color: Color) -> String
  case color
    Color.Red -> "red"
    Color.Green -> "green"
  end
end

def main() -> Void
  puts(color_name(Color.Green))
end

List every variant of a small enum in case and leave out _, so that a new variant fails the check where it must be handled. A _ is fine when many variants share one outcome:

# bad
enum Shape
  Dot
  Circle(Int)
end

def area(shape: Shape) -> Int
  case shape
    Shape.Circle(r) -> r * r * 3
    _ -> 0
  end
end

def main() -> Void
  puts(area(Shape.Circle(2)))
end
# good
enum Shape
  Dot
  Circle(Int)
end

def area(shape: Shape) -> Int
  case shape
    Shape.Circle(r) -> r * r * 3
    Shape.Dot -> 0
  end
end

def main() -> Void
  puts(area(Shape.Circle(2)))
end

Leaving a variant out with no _ does not compile:

# bad
enum Shape
  Dot
  Circle(Int)
end

def area(shape: Shape) -> Int
  case shape
    Shape.Circle(r) -> r * r * 3
  end
end

def main() -> Void
  puts(area(Shape.Dot))
end
Does not compile
error[CHECK-NON-EXHAUSTIVE-CASE]

Pipes #

Use a pipe for two or more |> steps on one value. Start with the value, and put one step per line inside parentheses (agentica fmt does it, and puts an empty line after any statement that takes several lines):

# good
def shout(text: String) -> String = text.upcase

def wrap(text: String, mark: String) -> String = "#{mark}#{text}#{mark}"

def banner(text: String) -> String
  (
    text
    |> shout()
    |> wrap("*")
    |> wrap(" ")
  )
end

def main() -> Void
  puts(banner("hi"))
end

One step is a plain call: shout(text), not text |> shout(). Three calls nested in first position are a pipe that starts with the innermost one: wrap(shout(trim(text)), "*") is trim(text) |> shout() |> wrap("*"). Two nested calls stay plain. A step may name a method of the value, and a method chain of three or more steps that passes lambdas is such a pipe: xs.map(->(x) { x * 2 }).select(->(x) { x > 2 }).sum is xs |> map(->(x) { x * 2 }) |> select(->(x) { x > 2 }) |> sum(), one step per line. A builtin is never piped with its type; write the method:

# bad
def main() -> Void
  puts("x" |> String.upcase())
end
Does not compile
error[CHECK-PIPE-METHOD]

Errors #

A function that can fail returns a Result and passes errors up with try. Use a halting form such as to_i! only when a failure is a bug, and say why in a comment. A value that may be missing, with no error to report, is an Optional (some(x) or none), not a Result:

# bad
def double_text(text: String) -> Int = text.to_i! * 2

def main() -> Void
  puts(double_text("21"))
end
# good
def double_text(text: String) -> Result[Int]
  n = try text.to_i
  ok(n * 2)
end

def main() -> Void
  case double_text("21")
    ok(n) -> puts(n)
    error(e) -> IO.warn(e.message)
  end
end

Write error text in lowercase, without a final period, and include the bad value (error("port out of range: 70000")). Handle errors at the edge of the program, such as main or a request handler. A parser returns a Result[T], not a struct with a valid or refused field:

# good
def parse_port(text: String) -> Result[Int]
  n = try text.to_i
  return error("port out of range: #{n}") if n < 1 or n > 65535

  ok(n)
end

def main() -> Void
  case parse_port("70000")
    ok(n) -> puts("port #{n}")
    error(e) -> IO.warn(e.message)
  end
end

A failure that a caller may branch on gets a kind, and the caller tests the kind with is_a? or reads e.code, never the message text:

# bad
def main() -> Void
  r: Result[Int] = error("unique failed: 19")
  case r
    ok(n) -> puts(n)
    error(e) if e.message.start_with?("unique failed") -> puts("duplicate")
    error(e) -> IO.warn(e.message)
  end
end
# good
def main() -> Void
  r: Result[Int] = error("unique failed", kind: "db.constraint", code: 19)
  case r
    ok(n) -> puts(n)
    error(e) if e.is_a?("db.constraint") -> puts("duplicate")
    error(e) -> IO.warn(e.message)
  end
end

Text and collections #

Build text with interpolation, not by joining pieces with + and .to_s. To wrap a long text, a few sentence-sized + pieces in parentheses are fine. Use a heredoc for text of several lines:

# bad
def line(name: String, count: Int) -> String = name + ": " + count.to_s + " items"

def main() -> Void
  puts(line("cart", 3))
end
# good
def line(name: String, count: Int) -> String = "#{name}: #{count} items"

def help() -> String
  <<~TEXT
    usage: tool FILE
    prints the lines of FILE
  TEXT
end

def main() -> Void
  puts(line("cart", 3))
  puts(help())
end

A String that grows by + in a loop is copied on every pass, so the loop is quadratic: push the pieces on a List and join them once after the loop.

Use a List for order, a Set for membership, a Map for lookup by key, and a struct for a record with known fields.

Effects #

Agentica has no monkey patching and a function is not a value, but a lambda is, so a test swaps an effect (a file read, the clock, an HTTP call, a random number) through a struct of Fn fields: the effects record. Build the real one once, at startup, from the configuration; a test builds another. The checker makes sure both have the same shape. The compiler does this with Workspace (compiler/modules/workspace.agc), which io/host.agc builds and app/ passes in. It plays the part of a behaviour plus a mock in other languages. Where a real server on localhost port 0 is as simple, use it instead of faking the network.

struct Effects
  read_file: Fn[String, Result[String]]
  now: Fn[Int]
end

def real_effects() -> Effects
  Effects(read_file: ->(path: String) { File.read_text(path) }, now: -> { Time.now_ms() })
end

def banner(effects: Effects, path: String) -> Result[String]
  name = try effects.read_file.call(path)
  ok("#{name.strip} at #{effects.now.call()}")
end

def main() -> Void
  Test.run([
    Test.test("banner reads the name and the clock") do
      fake = Effects(read_file: ->(_path) { ok("agentica\n") }, now: -> { 42 })
      Test.eq(banner(fake, "name.txt"), ok("agentica at 42"))
    end,
  ])
end

Check your code #

agentica fmt fixes the layout and agentica check refuses what is always a mistake. agentica lint suggests the rest of this guide that the syntax shows, and never fails the build unless you pass --strict (see Suggest style changes). Its rules, each with the part of the guide it comes from: