Functions and methods (I don't differentiate here) are the meat of any code we write. All our code is part of some function or method after all. And we use functions to call other functions, build re-usable functionalities and more.
That's why it's extremely important to write clean functions. Functions are made up of three main parts:
The naming of functions and methods is covered in the "Naming" section already. This section cheat sheet focuses on the parameters and body therefore.
The fewer parameters a function has, the easier it is to read and call (and the easier it is to read and understand statements where a function is called).
See this example:
def create_user(first_name, last_name, email, username, age, interests):
# Your implementation for creating a user goes here
# For example, you could create a User object and perform any necessary operations
user = {
'first_name': first_name,
'last_name': last_name,
'email': email,
'username': username,
'age': age,
'interests': interests
}
# Print or return the user data as needed
print(user)
# Alternatively, you can return the user dictionary if needed
# return user
# Example usage
create_user('Max', 'Max', '[email protected]', 'testers', 31, ['Sports', 'Cooking'])
Calling this function is no fun. We have to remember which parameters are required and in which order they have to be provided.
Reading this code is no fun either - for example, it's not immediately clear why we have two 'Max' values in the list.
How Many Parameters Are Okay?
Generally, fewer is better. Functions without paramters are of course very easy to read and digest. For example:
class User:
def create_session(self):
# Your implementation for creating a session goes here
print("Session created")
def save(self):
# Your implementation for saving the user goes here
print("User saved to the database")
# Example usage
user = User()
user.create_session()
user.save()
But "no parameters" is not always an option - after all it is the capability to take parameters that makes functions dynamic and flexible.
Thankfully, functions with one parameter are also straightforward:
import re
def is_valid_email(email):
# Basic email validation using a regular expression
email_regex = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$')
return bool(email_regex.match(email))
# Example usage
email = "[email protected]"
if is_valid_email(email):
print("Email is valid")
else:
print("Invalid email")
with open("example.txt", "w") as file:
data = "Hello, this is some data to be written to the file."
file.write(data)
Functions with two parameters can be okay - it really depends on the context and the kind of function.