Idiomatic Ant
Choose the form that makes the operation, data flow, and failure path clear.
Function calls and pipelines
Use dots for local operations
Keep short questions and actions close to their receiver. Keep compact chains that express one thought.
if !text.contains("ant") { return false }
if name.trim().isEmpty() { return false }
p.next()A select head is the exception: write it in namespace form, such as Channel.receive(jobs). Only that form is a head.
Count operations, not dots. Field access such as config.server.name locates a value. Name the value when the path becomes hard to follow.
Show transformations with pipes
Use pipes to show successive transformations. Put substantial stages on separate lines. Show namespace changes when they help readers follow the value.
orders
| Array.filter({ x.paid })
| Array.groupBy({ x.customer })
| Map.entries()
| Array.map(summarize)
| Array.sortBy({ x.customer })Keep comparable stages in the same style. Use dots inside callbacks for local operations. An aligned dot chain also works when the intermediate values remain clear.
Keep useful namespaces
Write the namespace when it explains an unfamiliar operation or gives several inputs equal attention.
Parser.cond(p, condition)
Point.distance(start, end)Use p.next() when the surrounding code makes its meaning clear. Choose a more descriptive receiver name, such as parser, as the scope grows.
A single pipe can also make a step clear:
parseConfig(text) | Result.wrapErr("parse ${path}") // Ok{ value: Config{ name: "app" } }Control flow
Handle exceptional cases early
Reject invalid input before continuing. Keep the successful path easy to follow. Use return to leave early and the final expression for the ordinary result.
let quantity = row.quantity.toInt()
if quantity == null {
return Result.fail("order ${row.id}: quantity must be an integer")
}
if quantity <= 0 {
return Result.fail("order ${row.id}: quantity must be positive")
}
Result.ok(Order{ id: row.id, quantity })Choose values with expressions
Use an if expression for a choice between values.
let noun = if summary.orders == 1 { "order" } else { "orders" }Keep conditions short. Prepare complex inputs before testing them, and keep ! close to the predicate. Use a guard when handling absence needs a long error message or several steps.
Absence and errors
Default missing values; validate supplied values
Use null for ordinary absence and Result for expected failure. Apply a default only when absence means the default is appropriate.
let setting = settings[key]
if setting == null { return Result.ok(fallback) }
boundedInt(setting.value, low, high)
| Result.wrapErr("line ${setting.line}, ${key}")Here, a missing port may use 8080; a supplied port=oops must report an error. A fallback after parsing would hide that invalid input.
Propagate failures and add useful context
Use try to propagate expected failures. Add context where the caller knows something the callee does not. Avoid repeating information already in the error.
let text = try File.read(path)
parseConfig(text) | Result.wrapErr("parse ${path}")Use panic and assert for broken program assumptions. Make the scope of try clear when combining it with pipes.
Callbacks and helpers
Name parameters when their roles matter
Use a short lambda for a simple operation. Name parameters when nested callbacks need both the outer and inner values.
orders
| Array.filter({ x.paid })
| Array.flatMap(func(order: Order): Array[string] {
order.items.map({ "${order.customer}: ${x.product}" })
})Extract helpers when their jobs deserve names or their bodies hide the main flow. Keep small callbacks beside the operations they explain.
Collections and loops
Ask for the result you need
Use some to ask whether a match exists, every to check all elements, find to get the first match, and filter to collect the matches.
let hasUnpaid = orders.some({ !x.paid })Choose operations whose stopping behavior fits the task. Keep predicate effects in mind when replacing a full scan with an operation that can stop early.
Stop on failure with a loop
Keep per-item validation, related updates, and early exits together.
let orders: Array[Order] = []
for row in rows {
orders.push(try parseOrder(row))
}
Result.ok(orders)This stops at the first error. An eager Array.map followed by Result.all evaluates every item before selecting the first error.
Write mutations and repeated actions as statements. A pipeline may end with an output operation.
Bindings and intermediate values
Prefer let for bindings that stay fixed. Use var for reassignment. A fixed binding can still hold an array, map, or record whose contents change.
Split a pipeline when a result is reused, controls a branch, deserves a name, or needs inspection. Name the value by its role, such as activeUsers.
Bind an intermediate result before printing it. println returns void and does not pass the value onward.
Resource lifetimes
Register cleanup beside acquisition
Put defer immediately after acquiring a resource. Choose the block that should own its lifetime.
let file = try File.open(path)
defer { file.close() }Check completion before reporting success
Return errors that affect the promised result. Deferred results are discarded, so close an output explicitly when closing may flush or fail.
func writeAndClose(output: File.Handle, lines: Array[string]): Result[void, Error] {
let buffered = output.buffered()
defer { buffered.close() }
for line in lines { try buffered.writeLine(line) }
buffered.close()
}The deferred close covers early exits. The final close reports a completion error. Make ownership clear when a function takes or returns an open resource.
Time
Write constant spans as literals
Write a constant span of hours and smaller units as a duration literal: Time.sleep(1s), Context.new(50ms), timeout: Time.Duration = 10m, not Time.duration(seconds: 1). Keep Time.duration for a span computed from a number.
let delay = if attempt == 0 { 500ms } else { Time.duration(seconds: attempt * 2) }
Time.sleep(delay, ctx: ctx)Write a calendar span with the constructor, such as Time.duration(days: 1), and a negative constant as Time.negate(5s). See Duration literals.
Changing style safely
Preserve optional chaining, interface calls, evaluation order, and failure behavior when changing style.
See Functions, Errors, Collections and sequences, and File.buffered for how these parts behave.
