Functional Programming
To write efficient and reusable code one should have a good grasp of functional programming.
What is functional programming?
If a single task of the program is done by a certain aspect of the code independent through the whole program that piece of code is known as a function.
From the definition, we can extract 2 conditions that make a function
Functions only do a single task.
Functions are independent which means functions can be called from anywhere. It can be called from the main function or it can be called from another function.
We have to write a program where we are given two integers num1
and num2
we have to add them up and say if the summation of num1
and num2
is even or odd
Driver function
if __name__=="__main__":
num1 = 10
num2 = 20
summation = num1 +num2
if summation%2==0:
print("Even")
else:
print("Odd")
What do we see here?
Yes, it solves the given problem but if you look carefully you will see this code is not reusable.
Because this is a small program you might find it easy to understand. but if the problem was bigger it would have been tough for anyone to understand the code you have written and if you wrote really bad code even you might be unable to understand your own code.
Functional Programming
def solution(n1,n2):
add = n1+n2
if add%2==0:
print("Even")
else:
print("Odd")
if __name__=="__main__":
num1 = 10
num2 = 20
solution(num1,num2)
Did we improve our code?
"No"
The issues we had are still there. The only thing we did is just put the whole code in a single function but, it's better to take baby steps rather than taking any steps at all.
Let's try to improve more.
def solution(n1,n2):
add = n1+n2
return add
def solution2(n):
if n%2==0:
print("Even")
else:
print("Odd")
if __name__=="__main__":
num1 = 10
num2 = 21
summation = solution(num1,num2)
solution2(summation)
Did we improve our code?
"Yes" we did.
Now our code is reusable but it's far off to be called a good code.
Let's address some issues
The naming of our function is ambiguous.
There is no return type. If anyone wants to find out what is the return type of the function he or she has to read the whole function just to know what type this function returned.
what happens if anyone passes a string as a parameter?
# adds two numbers
def add(num1: int , num2: int)->int:
return num1+num2
# checks a number is even or not
def is_even(number: int)->bool:
if number%2==0:
return True
return False
if __name__=="__main__":
num1 = 10
num2 = 20
if is_even(add(num1,num2)):
print("Even")
else:
print("Odd")
As we can see the code became much simpler to understand as well as issues we have addressed have been resolved.
Now you might be wondering why did I use print in the main
function rather than printing it in the sub-function?
The function should always return something it might be Bool
, it might be string
or it might be some other datatype
expect for None
or Null
. But a function should not have the task of printing it's the job of the main
function.