Site icon

Single responsibility design principle – Java & C++ (SOLID & example)

What is Single Responsibility Principle?

In ‘Principles of Object Oriented Design (OOD)’ Robert C Martin, define ‘responsibility‘ to be ‘a reason to change’.

Example: Employee class to analyze Single Responsible Principle

package org.learn.srp;

//enum representing department of employee
enum Department_t {
	HR, FINANCE, DISPLAY, CONSUMER_ELECTRONICS
}

// Dummy class ..It will contain data members/methods to interact with database
class DatabaseHandler {
}

public class Employee {
	String name;
	int empId;
	int salary;
	Department_t department;

	public Employee(String name, int emp_id, Department_t department) {
		// Update the data member;
	}

	int updateSalary(int new_slary) {
		// Update salary of employee
		// ...............
		// ........
		return 0;
	}

	void change_department(Department_t department) {
		// Change department of employee
		// ...code goes here
		// ......
	}
	
	int update_employee_database(DatabaseHandler db) {
		// Update salary of employee in database
		// ...............
		// ........
		return 0;
	}
};
//enum representing department of employee
typedef enum Department { HR,
    FINANCE,
    DISPLAY,
    CONSUMER_ELECTRONICS } Department_t;

// Dummy class ..It will contain data members/methods of database
class DatabaseHandler;
class Employee {
public:
    Employee(std::string name, int emp_id, Department_t department)
    {
        // Update the data member;
    }
    int update_salary(int new_slary)
    {
        // Update salary of employee
        // ...............
        // ........
        return 0;
    }
    void change_department(Department_t department)
    {
        // Change department of employee
        // ...code goes here
        // ......
    }
    int update_employee_database(DatabaseHandler& db)
    {
        // Update salary of employee in database
        // ...............
        // ........
        return 0;
    }

private:
    std::string m_name;
    int m_emp_id;
    int m_salary;
};

Analyze Employee class (Single Responsibility Principle):

The million-dollar question: Should update_employee_database method be part of the Employee class? Going by SLP, answer should be NO. Responsibility of updating the database should not be part of the Employee class. A change in update logic of employee table in database, could introduce a change in the Employee class, which is completely undesirable. Updating the database records should be handled by a separate class.
Developers unknowingly add more responsibility to a class, when there is bug fix or when they try to add a new functionality to a software.

The idea or aim behind SRP is to prevent unwanted and unrelated changes to a class. If we are achieving it then we are on right track to meet the objective of SRP.

Exit mobile version