ZC5003 - Function Definition Style
Descrição
Prefira a sintaxe nome() para definição de funções em vez de function nome.
Exemplo Problemático
#!/bin/zsh
# Sintaxe com keyword 'function'
function my_function() {
echo "Hello"
}
# Ou sem parênteses (ksh-style)
function my_other_function {
echo "World"
}
Diferenças Entre Sintaxes
1. Sintaxe nome() (POSIX, portátil)
#!/bin/zsh
# Padrão POSIX - funciona em bash, zsh, sh
my_function() {
echo "Hello"
}
# Com 'function' keyword (zsh/bash ksh-style)
function my_function() {
echo "Hello"
}
2. Comportamento Diferente
No bash:
function nameename()são quase idênticos- Mas
function namepode ter comportamento ksh se configurado
No zsh:
- Ambos funcionam igualmente
function namepermite omitir os parênteses
3. Portabilidade
| Sintaxe | bash | zsh | sh | ksh |
|---|---|---|---|---|
name() | ✅ | ✅ | ✅ | ✅ |
function name() | ✅ | ✅ | ❌ | ✅ |
function name | ✅ | ✅ | ❌ | ✅ |
Solução Correta
Use sintaxe POSIX para máxima compatibilidade:
#!/bin/zsh
# Padrão recomendado
my_function() {
local msg="Hello"
echo "$msg"
}
# Funções aninhadas (zsh)
outer() {
inner() {
echo "Inner function"
}
inner
}
Quando function Pode Ser Aceitável
A sintaxe function pode ser usada quando:
- Está em código zsh puro (sem necessidade de portabilidade)
- É uma convenção de equipe estabelecida
- Precisa de funcionalidades específicas do ksh
Exemplo zsh-específico:
#!/bin/zsh
# No zsh, 'function' permite omitir parênteses
function debug_print {
[[ -n "$DEBUG" ]] && print "$@"
}
Boas Práticas para Funções
#!/bin/zsh
# Use 'local' para variáveis internas
process_file() {
local filename="$1"
local -i line_count=0
while IFS= read -r line; do
((line_count++))
done < "$filename"
echo "$line_count"
}
# Retorne status explicitamente
check_valid() {
local input="$1"
if [[ -z "$input" ]]; then
return 1 # Error
fi
return 0 # Success
}
# Ou use 'true/false'
is_empty() {
[[ -z "$1" ]]
}