Solid Principles:
Solid Principle is an acronym for five design principles that help in creating more maintainable, flexible and scalable software. These Five principles were introduced by Robert C. Martin
1) Single Responsibility Principle(SRP):
A class should have only one reason to change, meaning it should have only one job or responsibility
class Employee
{
private String name;
private double salary;
public Employee(String name, double salary)
{
this.name=name;
this.salary=salary;
}
public double calculateSalary()
{
return salary*1.2;
}
public void generateReport()
{
System.out.println(“Generating employee report…”);
}
}
class SRPViolation
{
public static void main(String args[])
{
Employee emp=new Employee(“John”,50000);
System.out.println(“Salary=” +emp.calculateSalary());
emp.generateReport();
}
}
———————–
import java.io.*;
class Employee
{
private String name;
private double salary;
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Employee(String name,double salary)
{
this.name=name;//name=John
this.salary=salary;//salary=50000
}
}
class SalaryCalculator
{
public double calculateSalary(Employee employee)//
{
return employee.getSalary()*1.2;
}
}
class ReportGenerator
{
public void generateReport(Employee employee)
{
System.out.println(“Generating employee report for” +employee.getName());
}
}
class SRPExample
{
public static void main(String args[])
{
Employee emp=new Employee(“John”,50000);
SalaryCalculator calculator=new SalaryCalculator();
ReportGenerator reportGenerator=new ReportGenerator();
double revised=calculator.calculateSalary(emp);//object as an argument
System.out.println(“Revised salary for ” +emp.getName() + ” : ” + revised);
reportGenerator.generateReport(emp);//object as an argument
}
}
1 class–>1 task
II task–>new class