Lesson 3
Clean Code Practices with TypeScript: Mastering Functions and Methods
Introduction

Welcome to your next step in mastering Clean Code! 🚀 Previously, we emphasized the significance of naming conventions in clean coding. Now, we delve into the realm of functions and methods, which serve as the backbone of application logic and are crucial for code organization and execution. Structuring these functions effectively is vital for enhancing the clarity and maintainability of a codebase. In this lesson, we'll explore best practices and techniques to ensure our code remains clean, efficient, and readable.

Clean Functions at a Glance

Let's outline the key principles for writing clean functions:

  • Keep functions small. Small functions are easier to read, comprehend, and maintain.
  • Focus on a single task. A function dedicated to one task is more reliable and simpler to debug.
  • Limit arguments to three or fewer. Excessive arguments complicate the function signature and make it difficult to understand and use.
  • Avoid boolean flags. Boolean flags can obscure the code's purpose; consider separate methods for different behaviors.
  • Eliminate side effects. Functions should avoid altering external state or depending on external changes to ensure predictability.
  • Implement the DRY(Don't Repeat Yourself) principle. Employ helper functions to reuse code, minimizing redundancy and enhancing maintainability.

Now, let's take a closer look at each of these rules.

Keep Functions Small

Functions should remain small, and if they become too large, consider splitting them into multiple, focused functions. While there's no fixed rule on what counts as large, a common guideline is around 15 to 25 lines of code, often defined by team conventions.

Below, you can see the processOrder function, which is manageable but has the potential to become unwieldy over time:

TypeScript
1function processOrder(order: Order, inventory: Inventory, logger: Logger): void { 2 // Step 1: Validate the order 3 if (!order.isValid()) { 4 logger.log("Invalid Order"); 5 return; 6 } 7 8 // Step 2: Process payment 9 if (!order.processPayment()) { 10 logger.log("Payment failed"); 11 return; 12 } 13 14 // Step 3: Update inventory 15 inventory.update(order.getItems()); 16 17 // Step 4: Notify customer 18 order.notifyCustomer(); 19 20 // Step 5: Log order processing 21 logger.log("Order processed successfully"); 22}

Given that this process involves multiple steps, it can be improved by extracting each step into a dedicated private function, as shown below:

TypeScript
1function processOrder(order: Order, inventory: Inventory, logger: Logger): void { 2 if (!validateOrder(order, logger)) return; 3 if (!processPayment(order, logger)) return; 4 updateInventory(order, inventory); 5 notifyCustomer(order); 6 logOrderProcessing(logger); 7} 8 9function validateOrder(order: Order, logger: Logger): boolean { 10 if (!order.isValid()) { 11 logger.log("Invalid Order"); 12 return false; 13 } 14 return true; 15} 16 17function processPayment(order: Order, logger: Logger): boolean { 18 if (!order.processPayment()) { 19 logger.log("Payment failed"); 20 return false; 21 } 22 return true; 23} 24 25function updateInventory(order: Order, inventory: Inventory): void { 26 inventory.update(order.getItems()); 27} 28 29function notifyCustomer(order: Order): void { 30 order.notifyCustomer(); 31} 32 33function logOrderProcessing(logger: Logger): void { 34 logger.log("Order processed successfully"); 35}
Single Responsibility

A function should embody the principle of doing one thing only. If a function handles multiple responsibilities, it may include several logical sections. Below you can see the saveAndNotifyUser function, which is too lengthy and does multiple different things at once:

TypeScript
1async function saveAndNotifyUser(user: User, dataSource: DataSource, webClient: WebClient): Promise<void> { 2 // Save user to the database 3 const sql = "INSERT INTO users (name, email) VALUES (?, ?)"; 4 5 try { 6 const connection = await dataSource.getConnection(); 7 const statement = await connection.prepareStatement(sql); 8 statement.bind([user.getName(), user.getEmail()]); 9 await statement.execute(); 10 } catch (error) { 11 console.error('SQL Exception:', error); 12 } 13 14 // Send a welcome email to the user 15 try { 16 await webClient.post('/sendWelcomeEmail', user); 17 } catch (error) { 18 console.error('Failed to send email', error); 19 } 20}

To enhance this code, you can create two dedicated functions for saving the user and sending the welcome email. This results in dedicated responsibilities for each function and clearer code coordination:

TypeScript
1async function saveAndNotifyUser(user: User, dataSource: DataSource, webClient: WebClient): Promise<void> { 2 await saveUser(user, dataSource); 3 await notifyUser(user, webClient); 4} 5 6async function saveUser(user: User, dataSource: DataSource): Promise<void> { 7 const sql = "INSERT INTO users (name, email) VALUES (?, ?)"; 8 9 try { 10 const connection = await dataSource.getConnection(); 11 const statement = await connection.prepareStatement(sql); 12 statement.bind([user.getName(), user.getEmail()]); 13 await statement.execute(); 14 } catch (error) { 15 console.error('SQL Exception:', error); 16 } 17} 18 19async function notifyUser(user: User, webClient: WebClient): Promise<void> { 20 try { 21 await webClient.post('/sendWelcomeEmail', user); 22 } catch (error) { 23 console.error('Failed to send email', error); 24 } 25}
Limit Number of Arguments

Try to keep the number of function arguments to a maximum of three, as having too many can make functions less understandable and harder to use effectively. 🤔

Consider the saveAddress function below with five arguments, which makes the function less clean:

TypeScript
1function saveAddress(street: string, city: string, state: string, zipCode: string, country: string): void { 2 // Logic to save address 3}

A cleaner version encapsulates the details into an Address object, reducing the number of arguments and making the function signature clearer:

TypeScript
1function saveAddress(address: Address): void { 2 // Logic to save address 3}
Avoid Boolean Flags

Boolean flags in functions can create confusion, as they often suggest multiple pathways or behaviors within a single function. Instead, use separate methods for distinct behaviors. 🚫

The setFlag function below uses a boolean flag to indicate user status, leading to potential complexity:

TypeScript
1function setFlag(user: User, isAdmin: boolean): void { 2 // Logic based on flag 3}

A cleaner approach is to have distinct methods representing the different behaviors:

TypeScript
1function grantAdminPrivileges(user: User): void { 2 // Logic for admin rights 3} 4 5function revokeAdminPrivileges(user: User): void { 6 // Logic to remove admin rights 7}
Avoid Side Effects

A side effect occurs when a function modifies some state outside its scope or relies on something external. This can lead to unpredictable behavior and reduce code reliability.

Below, the addToTotal function demonstrates a side effect by modifying an external state:

TypeScript
1// Not Clean - Side Effect 2let total = 0; 3 4function addToTotal(value: number): number { 5 total += value; // modifies external state 6 return total; 7}

A cleaner version, calculateTotal, performs the operation without altering any external state:

TypeScript
1// Clean - No Side Effect 🌟 2function calculateTotal(initial: number, value: number): number { 3 return initial + value; 4}
Don't Repeat Yourself (DRY)

Avoid code repetition by introducing helper functions to reduce redundancy and improve maintainability.

The printUserInfo and printManagerInfo functions below repeat similar logic, violating the DRY principle:

TypeScript
1function printUserInfo(user: User): void { 2 console.log(`Name: ${user.name}`); 3 console.log(`Email: ${user.email}`); 4} 5 6function printManagerInfo(manager: Manager): void { 7 console.log(`Name: ${manager.name}`); 8 console.log(`Email: ${manager.email}`); 9}

To adhere to DRY principles, use a generalized printInfo function that operates on a Person type interface:

TypeScript
1interface Person { 2 name: string; 3 email: string; 4} 5 6function printInfo(person: Person): void { 7 console.log(`Name: ${person.name}`); 8 console.log(`Email: ${person.email}`); 9}
Summary

In this lesson, we learned that clean functions are key to maintaining readable and maintainable code. By keeping functions small, adhering to the Single Responsibility Principle, limiting arguments, avoiding side effects, and embracing the DRY principle, you set a strong foundation for clean coding. Next, we'll practice these principles to further sharpen your coding skills! 🎓

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.