Every software component should have one and one responsibility only
Software component can be class, method or module
Example, a swiss-army knife is a multipurpose tool that violates the single responsibility principle of software development, instead a knife is a good example that follows Single responsibility (as it can only be used for cutting unlike the Swiss-army knife that can be used for cutting, opening can, as a master key, scissors,etc)
Since the change is constant be it in the real world or in software development, the definition of the Single Responsibility Principle also changes accordingly
Every software component should have one and only one reason to change
There are three reasons for which change can occur in the below class Employee
- Change in Employee attribute
- Change in Database
- Change in Tax calculation
import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; /** * Employee class has details of employee * This class is responsible for saving employee details, getting tax of * employee and getting * details of employee like name, id, address, contact, etc. */ public class Employee { private String employeeId; private String employeeName; private String employeeAddress; private String contactNumber; private String employeeType; public void save() { String insert = MyUtil.serializeIntoString(this); Connection connection = null; Statement statement = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("jdbc://mysql://localhost:8080/MyDb", "root", "password"); statement = connection.createStatement(); statement.execute("insert into employee values (" + insert + ")"); } catch (Exception e) { e.printStackTrace(); } } public void calculateTax() { if (this.getEmployeeType().equals("fulltime")) { // tax calculation for full time employee } else if (this.getEmployeeType().equals("contract")) { // tax calculation for contract type employee } } public String getEmployeeId() { return employeeId; } public void setEmployeeId(String employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public String getEmployeeAddress() { return employeeAddress; } public void setEmployeeAddress(String employeeAddress) { this.employeeAddress = employeeAddress; } public String getContactNumber() { return contactNumber; } public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; } public String getEmployeeType() { return employeeType; } public void setEmployeeType(String employeeType) { this.employeeType = employeeType; } }
Since the SRP (Single Responsibility Principle) recommends only one reason for change in the class, we will have to make some modifications in the Employee class
Changes by SRP
Now, there is only one reason for which change can occur in Employee class
Reason for change: Change in Employee attribute
/** * Employee class has details of employee */ public class Employee { private String employeeId; private String employeeName; private String employeeAddress; private String contactNumber; private String employeeType; public void save() { new EmployeeRepository().save(this); } public void calculateTax() { new TaxCalculator().calculateTax(this); } public String getEmployeeId() { return employeeId; } public void setEmployeeId(String employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public String getEmployeeAddress() { return employeeAddress; } public void setEmployeeAddress(String employeeAddress) { this.employeeAddress = employeeAddress; } public String getContactNumber() { return contactNumber; } public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; } public String getEmployeeType() { return employeeType; } public void setEmployeeType(String employeeType) { this.employeeType = employeeType; } }
Also, there is only one reason for which change can occur in EmployeeRepository class
Reason for change: Change in database
import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class EmployeeRepository { public void save(Employee employee) { String insert = MyUtil.serializeIntoString(employee); Connection connection = null; Statement statement = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("jdbc://mysql://localhost:8080/MyDb", "root", "password"); statement = connection.createStatement(); statement.execute("insert into employee values (" + insert + ")"); } catch (Exception e) { e.printStackTrace(); } } }
Finally, there is only one reason for which change can occur in TaxCalculator class
Reason for change: Change in Tax calculation
public class TaxCalculator { public void calculateTax(Employee employee) { if (employee.getEmployeeType().equals("fulltime")) { // tax calculation for full time employee } else if (employee.getEmployeeType().equals("contract")) { // tax calculation for contract type employee } } }
Note: All the 3 classes now follow the Single Responsibility Principle, thus following both definitions
When creating classes or any software component keep in mind: Aim for high cohesion and loose coupling
Every software component should have one and one responsibility only and
Every software component should have one and only one reason to change
The above is the detailed content of Single Responsibility Principle. For more information, please follow other related articles on the PHP Chinese website!

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
