Lesson 3
Clean Functions and Methods in Scala
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 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:

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

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

Scala
1def processOrder(order: Order, inventory: Inventory, logger: Logger): Unit = 2 if !validateOrder(order, logger) then return 3 if !processPayment(order, logger) then return 4 updateInventory(order, inventory) 5 notifyCustomer(order) 6 logOrderProcessing(logger) 7 8private def validateOrder(order: Order, logger: Logger): Boolean = 9 if !order.isValid() then 10 logger.log("Invalid Order") 11 false 12 else 13 true 14 15private def processPayment(order: Order, logger: Logger): Boolean = 16 if !order.processPayment() then 17 logger.log("Payment failed") 18 false 19 else 20 true 21 22private def updateInventory(order: Order, inventory: Inventory): Unit = 23 inventory.update(order.items) 24 25private def notifyCustomer(order: Order): Unit = 26 order.notifyCustomer() 27 28private def logOrderProcessing(logger: Logger): Unit = 29 logger.log("Order processed successfully")
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 both too lengthy and does multiple different things at once:

Scala
1def saveAndNotifyUser(user: User, dataSource: DataSource, webClient: WebClient): Unit = 2 val sql = "INSERT INTO users (name, email) VALUES (?, ?)" 3 val connection = dataSource.getConnection() 4 val statement = connection.prepareStatement(sql) 5 6 try 7 statement.setString(1, user.name) 8 statement.setString(2, user.email) 9 statement.executeUpdate() 10 catch 11 case e: SQLException => e.printStackTrace() // Handle SQL exception 12 finally 13 connection.close() 14 15 webClient.post() 16 .uri("/sendWelcomeEmail") 17 .bodyValue(user) 18 .retrieve() 19 .onStatus(_.isError, _ => throw new RuntimeException("Failed to send email")) 20 .block()

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:

Scala
1def saveAndNotifyUser(user: User, dataSource: DataSource, webClient: WebClient): Unit = 2 saveUser(user, dataSource) 3 notifyUser(user, webClient) 4 5private def saveUser(user: User, dataSource: DataSource): Unit = 6 val sql = "INSERT INTO users (name, email) VALUES (?, ?)" 7 val connection = dataSource.getConnection() 8 val statement = connection.prepareStatement(sql) 9 10 try 11 statement.setString(1, user.name) 12 statement.setString(2, user.email) 13 statement.executeUpdate() 14 catch 15 case e: SQLException => e.printStackTrace() // Handle SQL exception 16 finally 17 connection.close() 18 19private def notifyUser(user: User, webClient: WebClient): Unit = 20 webClient.post() 21 .uri("/sendWelcomeEmail") 22 .bodyValue(user) 23 .retrieve() 24 .onStatus(_.isError, _ => throw new RuntimeException("Failed to send email")) 25 .block()
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:

Scala
1def saveAddress(street: String, city: String, state: String, zipCode: String, country: String): Unit = 2 // Logic to save address

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

Scala
1case class Address(street: String, city: String, state: String, zipCode: String, country: String) 2 3def saveAddress(address: Address): Unit = 4 // Logic to save address
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:

Scala
1def setFlag(user: User, isAdmin: Boolean): Unit = 2 // Logic based on flag

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

Scala
1def grantAdminPrivileges(user: User): Unit = 2 // Logic for admin rights 3 4def revokeAdminPrivileges(user: User): Unit = 5 // Logic to remove admin rights
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:

Scala
1// Not Clean - Side Effect 2var total: Int = 0 // external state 3 4def addToTotal(value: Int): Int = 5 total += value // modifies external state 6 total

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

Scala
1// Clean - No Side Effect 2def calculateTotal(initial: Int, value: Int): Int = 3 initial + value
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:

Scala
1def printUserInfo(user: User): Unit = 2 println(s"Name: ${user.name}") 3 println(s"Email: ${user.email}") 4 5def printManagerInfo(manager: Manager): Unit = 6 println(s"Name: ${manager.name}") 7 println(s"Email: ${manager.email}")

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

Scala
1def printInfo(person: Person): Unit = 2 println(s"Name: ${person.name}") 3 println(s"Email: ${person.email}")
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.