Course contentsShow
← Computer Science
Lesson 193 of 2,8725. Functions and ModularityFree lesson

Single Responsibility Principle

Learning why functions should perform one well-defined task for better code organization.

Single Responsibility Principle

What You'll Learn

You'll discover why each function should do one clear job — and only one — to keep your code clean and maintainable.

The Core Idea

The Single Responsibility Principle states that every function should have one well-defined task or responsibility. When a function tries to do too many things at once, it becomes harder to understand, test, and modify.

Think of it like kitchen tools: a knife cuts, a whisk whips, and a spatula flips. You could design one mega-tool that cuts, whips, and flips, but it would be clumsy and confusing. Each tool does its job well because it focuses on one thing.

Why It Matters

When functions follow this principle:

  • Easier to name: A function doing one task has a clear, descriptive name
  • Easier to debug: If something breaks, you know exactly where to look
  • Easier to reuse: Small, focused functions can be used in multiple places
  • Easier to test: You only need to verify one behavior per function

What This Looks Like

Instead of writing a function called processUserDataAndSendEmailAndUpdateDatabase(), you'd write three separate functions:

  • validateUserData()
  • sendConfirmationEmail()
  • updateUserInDatabase()

Each has a single, clear purpose. They're like building blocks you can arrange, test individually, and understand at a glance.

In Practice

Ask yourself: "Can I describe what this function does without using 'and' or 'or'?" If not, it probably does too much.

Key Takeaway: Write functions that do one thing well — they become easier to name, test, debug, and reuse throughout your program.