Use early return pattern
function foo(): void {
if (argument1.is_valid()) {
if (argument2.is_valid()) {
if (argument3.is_valid()) {
}
}
}
}
function foo(): void {
if (!argument1.is_valid()) return
if (!argument2.is_valid()) return
if (!argument3.is_valid()) return
}
Functions should do one thing
function email_clients(clients: Client[]) {
clients.forEach((client) => {
const client_record = database.lookup(client)
if (client_record.is_active()) {
email(client)
}
})
}
function email_clients(clients: Client[]) {
clients.filter(is_active_client).forEach(email)
}
function is_active_client(client: Client) {
const client_record = database.lookup(client)
return client_record.is_active()
}
Function names should say what they do
function add_to_date(date: Date, month: number): Date {
}
const date = new Date()
add_to_date(date, 1)
function add_month_to_date(date: Date, month: number): Date {
}
const date = new Date()
add_month_to_date(date, 1)
Don’t use flags as function parameters
function create_file(name: string, temp: boolean) {
if (temp) {
fs.create(`./temp/${name}`)
} else {
fs.create(name)
}
}
function create_temp_file(name: string) {
create_file(`./temp/${name}`)
}
function create_file(name: string) {
fs.create(name)
}
Avoid negative conditionals
function is_email_not_used(email: string): boolean {
}
if (is_email_not_used(email)) {
}
function is_email_used(email: string): boolean {
}
if (!is_email_used(node)) {
}
Remove dead code
function old_request_module(url: string) {
}
function request_module(url: string) {
}
const req = requestModule
function request_module(url: string) {
}
const req = requestModule