Clean Code: Functions
Functions should be small, do one thing, and do it well. They should have descriptive names and a small number of arguments.
Let's explore some examples in TypeScript to help you grasp the concept:
// Bad
function process(data: any[]): any[] {
const result = [];
for (const item of data) {
if (item.type === 'A') {
// ... perform logic specific to type A
} else if (item.type === 'B') {
// ... perform logic specific to type B
}
// ... more logic
}
return result;
}
// Good
function processTypeA(item: any): any {
// ... perform logic specific to type A
}
function processTypeB(item: any): any {
// ... perform logic specific to type B
}
function process(data: any[]): any[] {
const result = [];
for (const item of data) {
if (item.type === 'A') {
result.push(processTypeA(item));
} else if (item.type === 'B') {
result.push(processTypeB(item));
}
}
return result;
}