DEV Community

Cover image for Code Conciseness: Why Small Functions Make a Big Difference
Henry of Oracus 🇳🇬
Henry of Oracus 🇳🇬

Posted on • Originally published at Medium

Code Conciseness: Why Small Functions Make a Big Difference

Originally published on Medium: https://medium.com/@ezeanyimhenry/code-conciseness-why-small-functions-make-a-big-difference-78bf51357e32

Photo by Henry Ezeanyim

Welcome to the world of coding, where less really is more! In this article, we’re going to explore the idea of using shorter functions. Think of them as the superheroes of coding, they make your code easier to read, fix, and enjoy. So, get ready for a coding adventure that will show you why short and sweet is the way to go!

The Trouble with Long Functions

Photo by Shahadat Rahman on Unsplash

Have you ever looked at a piece of code and thought, “What on earth is going on here?” That’s what long functions can feel like. Here’s why it’s a good idea to keep your functions short and sweet:

  1. Easy to Understand: Short functions are like short stories, they’re easy to read and understand. Long functions, on the other hand, are like reading a never-ending book where you forget the beginning by the time you reach the end.
  2. Finding Mistakes: When something goes wrong in your code, short functions make it much easier to find the problem. It’s like looking for a lost sock in a tidy drawer instead of a messy room.
  3. Reusing Code: Short functions are like building blocks that you can use again and again. Long functions are more like giant, one-time-use machines that are hard to take apart.

Real-Life Examples: The Code Battle

Let’s see how this works with a real example. Imagine you’re building a program to calculate the total cost of items in a shopping cart. Here’s how it can be done with both long and short functions:

Long Function Approach:

function calculateTotalPrice($cart) {
$total = 0;
foreach ($cart as $item) {
$subtotal = $item['price'] * $item['quantity'];
$total = $total + $subtotal;
}
return $total;
}

Short Function Approach:

function calculateTotalPrice($cart) {
return array_sum(array_map(fn($item) => $item['price'] * $item['quantity'], $cart));
}

In this example, the short function approach not only has fewer lines of code but also makes it clearer what’s happening. It’s like upgrading from a clunky old calculator to a sleek, modern one, it’s faster and easier to use.

Conclusion: Embrace Short and Sweet Code

Photo by Henry Ezeanyim

In the world of coding, short and sweet is a superpower. Short functions make your code clear, easy to fix, and a joy to work with. So, embrace the idea of keeping your code concise, and you’ll find that coding becomes a happier and more efficient adventure. Your future self and your fellow coders will thank you!

Top comments (0)