Programming Paradigms

Session Overview

  • Objects
  • Functions
  • Classes
  • OOP & FP

Objects

  • Things!
  • Instances of classes
  • Specific data structure with its own set of properties and behaviors
  • Interacted with (manipulated, modified) through their properties and methods
  • Each object has a type
  • Objects have attributes and methods.
  • Examples of objects: integers, strings, lists, etc.

Example: Python

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print("Hello, my name is", self.name, "and I am", self.age, "years old.")

# Create a new Person object and call its greet method
person1 = Person("Alice", 25)
person1.greet()

# Create another Person object and call its greet method
person2 = Person("Bob", 30)
person2.greet()

Functions

  • Actions!
  • (If Objects are nouns, Functions are verbs)
  • Functions are blocks of code that perform a specific task.
  • They can take parameters and return values.
  • Example function:
def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))

Functions


Basic building blocks.

Reasons to use functions:

  • Code reusability: Functions can be defined once and then used multiple times throughout a program, reducing the amount of redundant code and making it easier to modify and maintain.

  • Modularity: Functions can be used to break a large program into smaller, more manageable parts, making it easier to understand and modify.

  • Abstraction: Functions can provide a higher level of abstraction by hiding the details of the code implementation and only exposing a well-defined interface.

  • Testing: Functions can be tested independently of the rest of the program, making it easier to identify and fix errors.

  • Efficiency: Functions can help to improve code efficiency by reducing the amount of redundant code and allowing for optimized code reuse.

  • Collaboration: Functions can be used to divide work among multiple programmers, making it easier to collaborate and work on different parts of a program simultaneously.


Functions are building blocks for both Object Oriented and Functional Programming languages.

Functions

How do we build functions?

Best Practices:

  • Function naming: Choose a descriptive and meaningful name for your function that accurately reflects what it does. Use a consistent naming convention that follows the language’s naming conventions and style guide.

  • Function input parameters: Define input parameters for your function that are clear and easy to understand. Avoid using too many parameters, or using parameters that have unclear meanings.

  • Function output: Define clear and concise output for your function. The output should accurately reflect what the function does, and should be consistent with the input parameters.

  • Function documentation: Provide clear documentation for your function that explains its purpose, input parameters, and output. Use comments to explain how the function works, and provide examples of how it can be used.

  • Function error handling: Include error handling in your function to handle unexpected input or errors. Provide informative error messages that help the user identify the problem and fix it.

  • Function design: Keep your functions modular and focused on a single task. Avoid adding unnecessary functionality to your function, and break down complex tasks into smaller, more manageable parts.

  • Function testing: Test your functions thoroughly to ensure that they work as expected. Write test cases that cover a range of input parameters, including edge cases and unexpected input.

Function Building:

Let’s build a function that calculates the euclidean distance between two points.

Classes

  • Classes are blueprints for creating objects.
  • They define the properties and behaviors of objects.
class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

    def bark(self):
        return "Woof!"

my_dog = Dog("Buddy", "Labrador")
print(my_dog.name)
print(my_dog.bark())

Session Overview

  • Objects
  • Functions
  • Classes
  • OOP & FP

Object Oriented Programming

  • Objects are Everything
  • Software is organized around data (objects) rather than functions/logic

OOP

Python is an Object-Oriented Programming (OOP) language.

Object-Oriented vs. Functional Programming

OOP

  • Objects and Classes are First Class Citizens
  • Uses objects and classes to model data and behavior
  • Encourages stateful objects with mutable state

FP

  • Functions are First Class Citizens
  • Uses functions as the primary building blocks
  • Emphasizes immutability and pure functions

Functional Programming

Map functions over objects.

# Example of map function
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x ** 2, numbers)
print(list(squared_numbers))

Ideal for Parallel Map Reduce Operations

Distributed Processing with FP

import multiprocessing

# Function to calculate the square of a number
def square(x):
    return x ** 2

if __name__ == "__main__":
    # List of numbers
    numbers = [1, 2, 3, 4, 5]

    # Create a multiprocessing Pool with 2 processes
    with multiprocessing.Pool(processes=2) as pool:
        # Use pool.map() to apply the square function to each number in parallel
        squared_numbers = pool.map(square, numbers)

    # Print the result
    print("Original Numbers:", numbers)
    print("Squared Numbers:", squared_numbers)

Note: Run this as a python script (not in the REPL) using Python 3.10 or above.