Código Autodocumentado
En esta página
El mejor comentario muchas veces es no necesitar ninguno. Nombres claros, tipos explícitos y constantes nombradas comunican la intención directamente — sin exigir que el lector consulte documentación separada.
Contraste entre nombres cortos y descriptivos; tipos explícitos y opcionales (str?); aliases de tipo Celsius/Meters/Seconds; constantes nombradas vs. números mágicos; struct ServerConfig y enum OrderStatus con doc comments en los campos; funciones pequeñas y enfocadas (is_even, clamp).
// ============================================================
// Self-Documenting Code in Zolo
// ============================================================
// Best practices: clear names, explicit types, and doc comments
// where the logic is not obvious.
use std::Array
// -- Descriptive names as documentation -----------------------
// Bad: short, meaningless names
fn f(a: int, b: int) -> int { return a + b }
fn g(x: [int]) -> int { return x.len() }
// Good: names that explain the intent
fn calculate_total(price: int, quantity: int) -> int {
return price * quantity
}
fn count_elements(list: [int]) -> int {
return list.len()
}
// -- Types as documentation -----------------------------------
// Explicit types communicate intent:
let age: int = 25
let name: str = "Alice"
let active: bool = true
let balance: float = 1234.56
// Optional types show that the value may be nil:
let email: str? = nil
let phone: str? = "+55 11 99999-0000"
// Type aliases for domain-specific values:
type Celsius = float
type Meters = float
type Seconds = float
let temperature: Celsius = 36.5
let distance: Meters = 100.0
let elapsed: Seconds = 9.58
print("Temp: {temperature}C")
print("{distance}m in {elapsed}s")
// -- Constants with meaningful names --------------------------
// Bad: magic numbers without explanation
// if speed > 343 { ... }
// Good: named constants
const SPEED_OF_SOUND = 343 // meters per second
const GRAVITY = 9.81 // m/s^2
const MAX_RETRIES = 3
const TIMEOUT_MS = 5000
fn is_supersonic(speed: float) -> bool {
return speed > SPEED_OF_SOUND
}
print("Mach 1+ ? {is_supersonic(400.0)}")
// -- Structs as data documentation ----------------------------
/// HTTP server configuration.
struct ServerConfig {
/// Address to listen on (e.g. "0.0.0.0")
host: str,
/// TCP port (e.g. 8080)
port: int,
/// Enable debug mode with verbose logs
debug: bool,
/// Maximum number of simultaneous connections
max_connections: int,
}
let config = ServerConfig {
host: "0.0.0.0",
port: 8080,
debug: false,
max_connections: 100,
}
print("Server: {config.host}:{config.port}")
// -- Enums document possible states ---------------------------
/// Status of an order in the system.
enum OrderStatus {
/// Order created, waiting for payment
Pending,
/// Payment confirmed, in preparation
Processing,
/// Order shipped for delivery
Shipped,
/// Successfully delivered
Delivered,
/// Order cancelled by user or system
Cancelled,
}
fn status_label(status: OrderStatus) -> str {
return match status {
OrderStatus::Pending => "Awaiting payment",
OrderStatus::Processing => "In preparation",
OrderStatus::Shipped => "Shipped",
OrderStatus::Delivered => "Delivered",
OrderStatus::Cancelled => "Cancelled",
}
}
let order = OrderStatus::Shipped
print("Status: {status_label(order)}")
// -- Small, focused functions ---------------------------------
// Each function does ONE thing and its name describes what:
fn is_even(n: int) -> bool {
return n % 2 == 0
}
fn is_positive(n: int) -> bool {
return n > 0
}
fn clamp(value: int, lo: int, hi: int) -> int {
if value < lo { return lo }
if value > hi { return hi }
return value
}
print("clamp(150, 0, 100) = {clamp(150, 0, 100)}")
print("clamp(-5, 0, 100) = {clamp(-5, 0, 100)}")
print("clamp(50, 0, 100) = {clamp(50, 0, 100)}")
Los aliases de tipo (type Celsius = float) no cambian el comportamiento
en tiempo de ejecución, pero hacen que las firmas de las funciones sean
autoexplicativas: el lector sabe que elapsed: Seconds es una duración, no
una distancia arbitraria.
Las constantes nombradas eliminan los "números mágicos" — SPEED_OF_SOUND
es más expresivo que 343 y evita errores de escritura.
Los structs y enums documentan los estados posibles: OrderStatus con
variantes Pending, Processing, Shipped, Delivered y Cancelled es
más claro que una cadena o entero sin restricciones.
Las funciones pequeñas y enfocadas (is_even, is_positive, clamp)
tienen nombres que funcionan como documentación: el código se lee como una
frase en lenguaje natural.
Consulta también