How to Use Functional Programming to Create Better Code [Technique Tuesdays]
How you can leverage the principles of Functional Programming to create code that is safer, more readable, and better less buggy
Hey, it’s your favorite cult leader here 🐱👤
On Tuesdays, I will cover problem-solving techniques that show up in software engineering, computer science, and Leetcode Style Questions📚📚📝📝.
To get access to all my articles and support my crippling chocolate milk addiction, consider subscribing if you haven’t already!
p.s. you can learn more about the paid plan here.
Clean code this, clean code.
You hear the term being thrown around a lot, but very rarely do people tell you some concrete steps on how you can write functions that are better. But as you may know, I am not like most people. A while back, I gave you 5 quick tips on how to write cleaner code. That was very helpful to a lot of you, and many have sent me requests for a follow-up.
Well my loves, this is your follow-up. In this article, we will be focusing on functional programming and how you can utilize some of the principles of functional programming to create code that is safer, more readable, and has fewer bugs. Because of their utility, these principles are applicable even if you’re not working in a functional setting. So these will help you vow everyone with your sicckkk programming skills.
Sound like a plan? Let’s get right into it.
Writing Better Code Using Functional Programming Principles-
1. Use pure functions: A pure function is a function that always returns the same output for the same input. This means that pure functions are free from side effects, which are changes to the state of the program outside of the function itself. This is a huge plus because side effects can make code difficult to understand and debug. Below is a simple example of a pure function:
def add_one(x): return x + 1
No matter how many times you call this function with the same input, it will always return the same output. Compare this to the following:
def increment_counter(): global counter counter += 1
This function changes the value of the global variable
counter
. This is a side effect. Because this function has a side effect, it is not a pure function. This example might seem silly, but side effects can break your code and are a nightmare to spot.Avoid mutable data: Mutable data is data that can be changed after it has been created. We use mutable data structures all the time in our code. But in code bases where things change all the time (like with threads), this can be a gold mine of bugs and errors. This is where we use immutable data structures. Immutable data structures are data structures that cannot be changed after they have been created. Compare the mutable list-
list = [1, 2, 3]
To this immutable:
tuple = (1, 2, 3)
This tuple cannot be changed after it has been created. You cannot add or remove elements from the tuple. Thus, you know how it will behave, making debugging/testing much easier.
Use recursion: Recursion is a technique for solving problems by breaking them down into smaller problems of the same type. This can be a powerful tool for writing concise and elegant code.
Now the first one is way easier to read because suprise suprise shorter code is usually easier to understand than code that is 10 times longer. Sometimes you want to ask yourself is the extra performance gain really worth it? The amount of hours wasted debugging the code. Is the iterative TowerOfHanoi faster than the Recursive TowerOfHanoi? Probably, but not by a big margin. Would I like to program Recursive problems like TowerOfHanoi using iteration? Hell no. Next we have another recursive function the Ackermann function: Using recursion:
Use higher-order functions: Higher-order functions are functions that can take other functions as arguments or return functions as their results. This can be a powerful tool for creating reusable code. This is great when you have general high-level behaviors, with differences being in specific implementations.
The code that we have written using HOFs is concise and modular. Each function is doing its own job and we are not repeating anything here.
This is a general template, where we apply a function to every element in the iterable-
def map(f, iterable): for element in iterable: yield f(element)
You can use the
map
function to square the elements of a list:numbers = [1, 2, 3] squared_numbers = map(lambda x: x * x, numbers)
Now if we wanted the square root of every element, all we have to do is change the lambda we are passing into the map function. Everything else stays the same.
Use lazy evaluation: Lazy evaluation is a technique for evaluating expressions only when they are needed. This can be a powerful tool for improving performance and reducing memory usage. We covered this in more detail in the article- How Algorithms Exploit Laziness. Make sure you check that out for more details.
Functional programming is considered very esoteric by some, but the principles in functional programming will help you boost your programming skills. And as a bonus- functional programming will take your recursion to the next level. If you’d like to know more about how you can use functional programming to level up in recursion, read the following article.
That is it for this piece. I appreciate your time. As always, if you’re interested in reaching out to me or checking out my other work, links will be at the end of this email/post. If you like my writing, I would really appreciate an anonymous testimonial. You can drop it here. And if you found value in this write-up, I would appreciate you sharing it with more people. It is word-of-mouth referrals like yours that help me grow.
Save the time, energy, and money you would burn by going through all those videos, courses, products, and ‘coaches’ and easily find all your needs met in one place at ‘Tech Made Simple’! Stay ahead of the curve in AI, software engineering, and the tech industry with expert insights, tips, and resources. 20% off for new subscribers by clicking this link. Subscribe now and simplify your tech journey!
Using this discount will drop the prices-
800 INR (10 USD) → 640 INR (8 USD) per Month
8000 INR (100 USD) → 6400INR (80 USD) per year
Reach out to me
Use the links below to check out my other content, learn more about tutoring, reach out to me about projects, or just to say hi.
If you like my writing, I would really appreciate an anonymous testimonial. You can drop it here.
To help me understand you fill out this survey (anonymous)
Small Snippets about Tech, AI and Machine Learning over here
Check out my other articles on Medium. : https://rb.gy/zn1aiu
My YouTube: https://rb.gy/88iwdd
Reach out to me on LinkedIn. Let’s connect: https://rb.gy/m5ok2y
My Instagram: https://rb.gy/gmvuy9
My Twitter: https://twitter.com/Machine01776819