DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

Single Responsibility Principle

What is single responsibility principle

It defines that each and every class or module should have single responsibility, in other word we can say that every object should have single responsibility and there is only one reason to change it (SRP states that a class should have only one reason to change, meaning it should have only one responsibility.)

Purpose/Objective:

The Single Responsibility Principle (SRP) is one of the SOLID principles, which is a set of guidelines for writing clean and maintainable code,This principle helps in achieving better code organisation, maintenance, and re-usability.

Example:

class Employee, It should contain only relevant function in it like calculateBonus, printDetails etc. we should not include irrelevant function in it.

#include <iostream>
#include <string>

// Example class representing an Employee
class Employee {
private:
    std::string name;
    int employeeId;
    float salary;

public:
    Employee(const std::string& name, int employeeId, float salary)
        : name(name), employeeId(employeeId), salary(salary) {}

    // Method to calculate the annual bonus for the employee
    float calculateBonus() const {
        // Complex bonus calculation logic
        // ...
        return salary * 0.1f;  // Just a dummy calculation for demonstration
    }

    // Method to print employee details
    void printDetails() const {
        std::cout << "Name: " << name << std::endl;
        std::cout << "Employee ID: " << employeeId << std::endl;
        std::cout << "Salary: $" << salary << std::endl;
        std::cout << "Bonus: $" << calculateBonus() << std::endl;
    }
};

int main() {
    // Creating an Employee object
    Employee employee("John Doe", 12345, 5000.0f);

    // Printing employee details
    employee.printDetails();

    return 0;
}

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer