4.5 Functions
Table of Contents
Why Functions Matter
When you write code, you often repeat the same steps again and again. Functions let you:
- Group related steps into one block of code
- Give that block a name
- Reuse it many times with different inputs
Instead of copying the same code 10 times, you write it once as a function and call it 10 times.
In almost every backend you build, you will create lots of functions: for validating data, talking to a database, formatting responses, and much more.
Key idea: A function is a named block of code that can take inputs, perform actions, and optionally return a result.
In this chapter we focus on the concepts of functions, not on any specific programming language syntax, although examples will look similar to Python or pseudocode.
Defining a Function
A function definition usually includes:
- Name
- Parameters (inputs)
- Body (the code to run)
- Optional return value
Here is a very generic pseudocode structure:
function function_name(parameter1, parameter2, ...):
# function body
do something
return some_valueExample:
function greet(name):
message = "Hello, " + name
return messageHere:
greetis the function namenameis a parameter- The body creates a message
- The function returns the message
You can think of it as defining a small machine that takes some input and produces some output.
Calling a Function
Defining a function does not run its code. You run it by calling it.
Using the greet function from before:
result = greet("Alice")
print(result) # "Hello, Alice"What happens when you call:
"Alice"is passed into the parametername- The body runs, builds the message
- The function returns the message
- That message is stored in
result
You can call the same function with different arguments:
print(greet("Bob")) # "Hello, Bob"
print(greet("Charlie")) # "Hello, Charlie"This is much better than writing the greeting logic three times.
Parameters and Arguments
Parameters are the variable names in the function definition.
Arguments are the actual values you pass when you call the function.
Example:
function add(a, b):
return a + b
sum1 = add(2, 3) # 2 and 3 are arguments
sum2 = add(10, 5) # 10 and 5 are arguments- In the definition,
aandbare parameters - In the call
add(2, 3), the values2and3are arguments
A simple mapping:
| Concept | In definition | In call |
|---|---|---|
| Name | add | add |
| Parameters | a, b | |
| Arguments | 2, 3 |
You can have functions with:
- No parameters
- One parameter
- Many parameters
Example with no parameters:
function show_welcome():
print("Welcome to the API!")Example with multiple parameters:
function build_full_name(first_name, last_name):
return first_name + " " + last_nameReturn Values
A function can:
- Return a value
- Or not return anything (often returns an implicit "nothing" value, like
nullorNone)
The return statement:
- Ends the function execution
- Sends a value back to the caller
Example:
function multiply(a, b):
product = a * b
return product
result = multiply(4, 5) # result is 20
If a function has no explicit return, or just return without a value, many languages return a special "no value" object.
Example:
function log_request(url):
print("Request received for:", url)
# no return statement hereThis function is used for its side effect (logging), not for its result.
Returning early
You can use return to exit a function early.
function divide(a, b):
if b == 0:
print("Cannot divide by zero")
return null # exit early
return a / bThis is common in backend code for validation and error handling.
Function Scope and Variables
Every function has its own scope. Scope decides where a variable is visible.
Typical rules:
- Variables created inside a function are local to that function
- Variables outside the function cannot be accessed inside, unless special rules are used
- Local variables are usually destroyed after the function finishes
Example:
global_message = "Hello from outside"
function show_messages():
local_message = "Hello from inside"
print(global_message) # often allowed, reading from outer scope
print(local_message) # ok
show_messages()
print(local_message) # ERROR, not visible hereIn many languages:
- You can read outer variables inside a function
- But if you try to assign to them, you might create a new local variable with the same name, unless you explicitly mark it as global or nonlocal
Understanding scope helps you avoid bugs where variables accidentally overwrite each other.
Rule: A local variable inside a function does not exist outside that function.
Practical backend example:
function get_user_full_name(user):
full_name = user.first_name + " " + user.last_name
return full_name
# full_name is not visible herePure Functions vs Functions with Side Effects
Backend code has a lot of side effects: database writes, network calls, logging, sending emails. It is useful to distinguish:
| Type | Description | Example |
|---|---|---|
| Pure function | Depends only on inputs, no side effects | add(a, b), normalize_email(email) |
| Impure function | Reads / writes external state, causes side effects | save_user_to_db(user), send_email() |
Example pure function:
function sanitize_username(username):
username = trim_spaces(username)
username = to_lowercase(username)
return usernameSame input, same output, no database, no network.
Example with side effect:
function send_welcome_email(user_email):
subject = "Welcome!"
body = "Thanks for registering."
email_service.send(user_email, subject, body) # side effectYou often want your business rules as pure as possible, and keep side effects at the boundaries. This makes code easier to test.
Functions as Building Blocks
Functions help you break a big task into smaller steps.
Imagine a backend endpoint that registers a user:
- Validate the input
- Check if the email is available
- Hash the password
- Save the user
- Send a welcome email
Without functions, this might be one long, messy block.
With functions:
function register_user(request_data):
validated_data = validate_registration_data(request_data)
ensure_email_is_available(validated_data.email)
password_hash = hash_password(validated_data.password)
user = create_user_record(validated_data, password_hash)
send_welcome_email(user.email)
return userEach step could be its own function:
function validate_registration_data(data): ...
function ensure_email_is_available(email): ...
function hash_password(password): ...
function create_user_record(data, password_hash): ...
function send_welcome_email(email): ...Benefits:
- Easier to read
- Easier to test each function separately
- You can reuse parts in other features (e.g., password hashing)
Common Function Patterns in Backend Code
While syntax differs by language, backends often have similar function patterns.
1. Validation functions
Check if input data is correct.
function is_valid_email(email):
if "@" not in email:
return false
if "." not in email:
return false
return true2. Conversion / transformation functions
Transform data from one form to another.
function to_response_user(user):
return {
"id": user.id,
"name": user.full_name,
"email": user.email
}3. Helper functions
Small utility tasks you need often.
function generate_order_number():
timestamp = current_timestamp()
random_part = random_digits(4)
return "ORD-" + timestamp + "-" + random_part4. Wrapper / orchestration functions
Call several other functions in sequence.
function process_order(order_request):
validated = validate_order(order_request)
stock = reserve_stock(validated.items)
payment_result = charge_payment(validated.payment_info)
save_order(validated, stock, payment_result)
send_order_confirmation(validated.user_email)Avoiding Common Mistakes
Beginners often run into the same problems with functions.
Forgetting to return a value
function sum(a, b):
result = a + b
# forgot: return result
x = sum(2, 3) # x is null / NoneAlways check if the function should return something.
Modifying inputs unexpectedly
Some languages let you change objects passed into functions. That can surprise callers.
function add_default_role(user):
user.roles.append("user") # changes the original object
return userYou must decide if this behavior is expected. Document it or copy the data instead.
Doing too much in one function
A function that:
- Validates input
- Talks to 3 external services
- Writes to 2 databases
- Builds an HTTP response
is hard to understand and test.
Try to follow a simple rule:
Guideline: A function should do one thing, and do it well.
If you find many and words when you describe what a function does, consider splitting it.
Summary
In this chapter you learned:
- A function is a named block of code that can take inputs and return a result.
- You define a function once and call it many times.
- Parameters are the names in the definition, arguments are the values in the call.
returnends a function and sends a value back to the caller.- Variables inside a function are local and not visible outside.
- You can separate pure logic from side effects to make code easier to test.
- Functions are the main building blocks for structuring backend code into clear, reusable parts.
As you continue through backend topics, you will see functions everywhere: in web frameworks, database libraries, and your own code. Understanding these basics will make the rest of the course much easier to follow.
Views: 8
KAHIBARO