object-oriented programming

test

Personal Log

作者: n5321

procedural programming

https://www.youtube.com/watch?v=pTB0EiLXUC8&t=304s

the best functions are those with no parameters! uncle bob

oop value

reduce complexity+increase reusability+ isolate impact of changes+Eliminate redundant code+refactor ugly switch/case statements.

pop有点像是把所有的文档放在同一个文件夹——spaghetti

oop就是分了很多个子文件夹,这个时候一切东西找起来就很方便了!

So, What Does "Best Functions Have No Parameters" Mean?

Not about eliminating data → but storing it inside objects instead of passing it everywhere. Encapsulation → The object holds state, so functions need fewer arguments. Readability → Shorter function calls, avoiding long parameter lists. Extensibility → If we add currency, we only modify the class, not every function call.

💡 Rule of Thumb:

  • If a function operates on an object, prefer using attributes over parameters.

  • If a function is purely a utility (e.g., math.sqrt(x)), parameters are fine.

🧠 Thinking in Objects, Not Steps – A Deep Dive

The key to object-oriented thinking (OOT) is shifting your focus from actions (procedures) to objects that interact with each other. 从解决一个问题转向解决一系列问题。 Instead of breaking a problem into a sequence of steps, you break it into entities (objects) that have their own data and behavior. 从用一系列步骤来解决一个问题(菜谱recipe)转向各个"责任人"合作解决问题。

走向联邦制、事业部制。


🌟 Step-by-Step Breakdown: Coffee Machine Example ☕

Let’s say we need to design a coffee machine.

🚫 Procedural Thinking (Step-by-Step Mindset)

A procedural programmer thinks in steps:

1️⃣ Heat the water. 2️⃣ Add coffee to the water. 3️⃣ Pour the coffee into a cup. 4️⃣ Serve the coffee.

💻 Procedural Code (Functions Only, No Objects)

python复制编辑def heat_water():
  print("Heating water...")

def add_coffee():
  print("Adding coffee...")

def pour_into_cup():
  print("Pouring coffee into cup...")

def serve():
  print("Serving coffee!")

# Run the process
heat_water()
add_coffee()
pour_into_cup()
serve()

👉 What’s wrong with this?

  • No structure – Everything is just a function. There’s no way to reuse these components easily.

  • No data encapsulation – If we need to change how water is heated, we must modify multiple functions.

  • Hard to extend – What if we add milk or sugar? We’d have to change every function!

以解决当前问题为核心,没有对于未来的类似问题的解决方案(spaghetti),太多的指令交织在一起。


✅ Object-Oriented Thinking (Thinking in Objects & Responsibilities)

Now, let’s identify objects instead of steps:

  • 🔥 WaterHeater → Handles heating water.

  • CoffeeDispenser → Adds coffee to the cup.

  • 🥤 Cup → Holds the final coffee.

  • 🎛️ CoffeeMachine → Coordinates the entire process.

💡 Instead of asking: "What steps do I follow?" We now ask: "Which objects interact, and how?"


💻 Object-Oriented Code (Encapsulation & Reusability)

class WaterHeater:
  def heat(self):
      print("Heating water to 90°C...")

class CoffeeDispenser:
  def add_coffee(self):
      print("Dispensing coffee...")

class Cup:
  def fill(self):
      print("Filling the cup with coffee...")

class CoffeeMachine:
  def __init__(self):
      self.water_heater = WaterHeater()
      self.dispenser = CoffeeDispenser()
      self.cup = Cup()

  def make_coffee(self):
      self.water_heater.heat()
      self.dispenser.add_coffee()
      self.cup.fill()
      print("Coffee is ready! ☕")

# Use the CoffeeMachine
machine = CoffeeMachine()
machine.make_coffee()

👉 What’s better about this? Encapsulation – Each object only handles its own job. Reusability – We can now reuse WaterHeater for tea or soup! Extensibility – We can easily add milk, sugar, or different coffee types without breaking the existing code.


🎯 Object-Oriented Thinking: Key Takeaways

ConceptProcedural Thinking 🚫Object-Oriented Thinking
FocusSteps & actionsObjects & interactions
Data HandlingUses global/shared dataEncapsulated inside objects
Code OrganizationFunctions everywhereWell-structured classes
ReusabilityHard to reuse functionsEasy to reuse objects
ScalabilityHard to add new featuresEasy to extend

📝 How to Practice Object-Oriented Thinking

To master thinking in objects, follow these steps when designing a program:

1️⃣ Identify Nouns (Objects) – Find real-world entities in the problem. 2️⃣ Find Responsibilities (Methods) – What does each object do? 3️⃣ Determine Relationships – How do objects interact with each other? 4️⃣ Encapsulate & Refactor – Keep responsibilities inside the objects.

Developing an Object-Oriented Thinking Style

If you're struggling to break a program into objects, you need to shift your thinking from "writing procedures" (imperative programming) to "designing interactions between objects" (object-oriented programming).


1️⃣ Change Your Mindset: Think in Objects, Not Steps

Instead of thinking "What steps do I take to solve this?", think "What objects interact to solve this?"

💡 Example: Making a Coffee Machine

  • Procedural Thinking: "First, heat water → then add coffee → then serve it."

  • Object-Oriented Thinking: "I have a WaterHeater, a CoffeeDispenser, and a Cup. How do they work together?"


2️⃣ Identify Objects from Real-World Concepts

Whenever you write a program, ask yourself:

  • What real-world things exist in my problem? (People, items, systems)

  • What actions do these things perform?

  • What data do they store?

💡 Example: Building a Library System

ObjectAttributes (Data)Methods (Actions)
BookTitle, Author, ISBNBorrow(), Return()
MemberName, Membership IDRegister(), PayFees()
LibraryBooks, MembersAddBook(), LendBook()

3️⃣ Group Related Data & Behavior

A function describes a step, while a class groups related things.

Procedural Approach (Messy, No Structure)

python复制编辑books = []

def add_book(title, author):
  books.append({"title": title, "author": author})

def display_books():
  for book in books:
      print(book["title"], "by", book["author"])

Object-Oriented Approach (Encapsulated & Structured)

python复制编辑class Book:
  def __init__(self, title, author):
      self.title = title
      self.author = author

  def display(self):
      print(f"{self.title} by {self.author}")

book1 = Book("1984", "George Orwell")
book1.display() # 1984 by George Orwell
  • Now each book remembers its own data.

  • The display() function belongs to the book, instead of being a separate function.


4️⃣ Look for Relationships Between Objects

Objects don’t exist alone! Think about how they interact.

💡 Example: E-Commerce System (Orders, Customers, Products)

  • A Customer places an Order

  • An Order contains Products

  • A Product has a price

python复制编辑class Product:
  def __init__(self, name, price):
      self.name = name
      self.price = price

class Order:
  def __init__(self):
      self.items = []

  def add_product(self, product):
      self.items.append(product)

  def total_price(self):
      return sum(p.price for p in self.items)

# Usage
p1 = Product("Laptop", 1000)
p2 = Product("Mouse", 50)

order = Order()
order.add_product(p1)
order.add_product(p2)
print(order.total_price()) # 1050
  • Objects talk to each other! Order calls Product’s data.

  • Encapsulation: Each class handles only its own responsibility.


5️⃣ Recognize Common Object-Oriented Patterns

As you practice OOP, start recognizing patterns:

  • Encapsulation → Keep object data private (self.name)

  • Inheritance → Use a parent-child relationship (class ElectricCar(Car))

  • Polymorphism → Write code that works for multiple types of objects

💡 Example: Inheritance

python复制编辑class Animal:
  def speak(self):
      return "I make a sound"

class Dog(Animal):
  def speak(self):
      return "Woof!"

class Cat(Animal):
  def speak(self):
      return "Meow!"

animals = [Dog(), Cat()]
for a in animals:
  print(a.speak()) # Woof! Meow!
  • "speak()" is different for each type of object.

  • But the animals list doesn’t care if it’s a Dog or Cat—they both follow the same pattern!


6️⃣ Practice: Convert Simple Functions into Objects

Challenge: Build a Car System 🚗

Steps:

  1. Identify objects → Car, Engine, Driver

  2. Define attributes → Car has brand, speed

  3. Define methods → Car can accelerate(), brake()

Try converting this procedural approach:

python复制编辑speed = 0

def accelerate():
  global speed
  speed += 10

def brake():
  global speed
  speed -= 5

accelerate()
print(speed) # 10

Into an OOP version:

python复制编辑class Car:
  def __init__(self, brand):
      self.brand = brand
      self.speed = 0

  def accelerate(self):
      self.speed += 10

  def brake(self):
      self.speed -= 5

car = Car("Tesla")
car.accelerate()
print(car.speed) # 10

Now, each car manages its own speed instead of using a global variable!


📌 Summary: How to Develop an Object-Oriented Thinking Style

Think in objects, not steps Find real-world objects in your program Group data & behavior inside a class Look for relationships between objects Recognize common patterns like inheritance & polymorphism Practice refactoring procedural code into OOP

Would you like more exercises or a real-world project breakdown? 🚀

The main difference between a function and a class is in their purpose and usage in a program. Here’s a breakdown:


1️⃣ Function vs. Class: Basic Concept

🔹 Function → A block of code that performs a specific task and returns a result. 🔹 Class → A blueprint for creating objects, grouping related data (attributes) and behaviors (methods) together.

4️⃣ When to Use Function vs. Class

Use a function when:

  • The task is simple and stateless (e.g., a math operation).

  • You don’t need to store any persistent data between calls.

Use a class when:

  • You need to store state (data) and perform operations on it.

  • You are modeling a real-world entity (e.g., a User, Car, Account).

  • You need multiple instances that behave independently.

Conclusion

  • Use functions for small, independent tasks

  • Use classes when you need structure, state, and objects

Do you need an example based on your personal app?

🚀 Developing an Object-Oriented Thinking Style

If you're struggling to break a program into objects, you need to shift your thinking from "writing procedures" (imperative programming) to "designing interactions between objects" (object-oriented programming).


1️⃣ Change Your Mindset: Think in Objects, Not Steps

Instead of thinking "What steps do I take to solve this?", think "What objects interact to solve this?"

💡 Example: Making a Coffee Machine

  • Procedural Thinking: "First, heat water → then add coffee → then serve it."

  • Object-Oriented Thinking: "I have a WaterHeater, a CoffeeDispenser, and a Cup. How do they work together?"

The four core principles of OOP are Encapsulation, Abstraction, Inheritance, and Polymorphism.

Encapsulation: "Data Hiding & Protection"

🔹 Definition: Encapsulation is the process of bundling data (attributes) and methods (behavior) into a single unit (a class) and restricting direct access to some of the object’s components.

🔹 Why? ✅ Prevents accidental modification of data ✅ Protects internal object state ✅ Controls how data is accessed and modified

2️⃣ Abstraction: "Hiding Complexity, Showing Essentials"

🔹 Definition: Abstraction focuses on exposing only the necessary details while hiding the complex implementation.

🔹 Why? ✅ Simplifies usage by focusing on "what" rather than "how" ✅ Reduces complexity for users ✅ Prevents unnecessary dependencies

3️⃣ Inheritance: "Code Reusability & Hierarchy"

🔹 Definition: Inheritance allows a class to acquire properties and behavior from another class (parent → child).

🔹 Why? ✅ Reduces redundant code ✅ Promotes code reuse ✅ Allows for easy modifications and extensions

4️⃣ Polymorphism: "Same Interface, Different Behavior"

🔹 Definition: Polymorphism allows different classes to have the same interface (method names) but different implementations.

🔹 Why? ✅ Supports flexible and reusable code ✅ Makes programs more maintainable ✅ Reduces dependencies on specific implementations