KAHIBARO
Discord Login Register

4.5 Functions

Why Functions Matter

When you write code, you often repeat the same steps again and again. Functions let you:

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:

  1. Name
  2. Parameters (inputs)
  3. Body (the code to run)
  4. Optional return value

Here is a very generic pseudocode structure:

text
function function_name(parameter1, parameter2, ...):
    # function body
    do something
    return some_value

Example:

text
function greet(name):
    message = "Hello, " + name
    return message

Here:

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:

text
result = greet("Alice")
print(result)          # "Hello, Alice"

What happens when you call:

  1. "Alice" is passed into the parameter name
  2. The body runs, builds the message
  3. The function returns the message
  4. That message is stored in result

You can call the same function with different arguments:

text
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:

text
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

A simple mapping:

ConceptIn definitionIn call
Nameaddadd
Parametersa, b
Arguments2, 3

You can have functions with:

Example with no parameters:

text
function show_welcome():
    print("Welcome to the API!")

Example with multiple parameters:

text
function build_full_name(first_name, last_name):
    return first_name + " " + last_name

Return Values

A function can:

The return statement:

Example:

text
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:

text
function log_request(url):
    print("Request received for:", url)
    # no return statement here

This function is used for its side effect (logging), not for its result.

Returning early

You can use return to exit a function early.

text
function divide(a, b):
    if b == 0:
        print("Cannot divide by zero")
        return null   # exit early
    return a / b

This 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:

Example:

text
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 here

In many languages:

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:

text
function get_user_full_name(user):
    full_name = user.first_name + " " + user.last_name
    return full_name
# full_name is not visible here

Pure 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:

TypeDescriptionExample
Pure functionDepends only on inputs, no side effectsadd(a, b), normalize_email(email)
Impure functionReads / writes external state, causes side effectssave_user_to_db(user), send_email()

Example pure function:

text
function sanitize_username(username):
    username = trim_spaces(username)
    username = to_lowercase(username)
    return username

Same input, same output, no database, no network.

Example with side effect:

text
function send_welcome_email(user_email):
    subject = "Welcome!"
    body = "Thanks for registering."
    email_service.send(user_email, subject, body)  # side effect

You 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:

  1. Validate the input
  2. Check if the email is available
  3. Hash the password
  4. Save the user
  5. Send a welcome email

Without functions, this might be one long, messy block.

With functions:

text
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 user

Each step could be its own function:

text
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:

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.

text
function is_valid_email(email):
    if "@" not in email:
        return false
    if "." not in email:
        return false
    return true

2. Conversion / transformation functions

Transform data from one form to another.

text
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.

text
function generate_order_number():
    timestamp = current_timestamp()
    random_part = random_digits(4)
    return "ORD-" + timestamp + "-" + random_part

4. Wrapper / orchestration functions

Call several other functions in sequence.

text
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

text
function sum(a, b):
    result = a + b
    # forgot: return result
x = sum(2, 3)   # x is null / None

Always check if the function should return something.

Modifying inputs unexpectedly

Some languages let you change objects passed into functions. That can surprise callers.

text
function add_default_role(user):
    user.roles.append("user")    # changes the original object
    return user

You must decide if this behavior is expected. Document it or copy the data instead.

Doing too much in one function

A function that:

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:

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

Comments

Please login to add a comment.

Don't have an account? Register now!