One example of the SOLID principles in Java is the Single Responsibility Principle (SRP). It states that a class should have only one reason to change, meaning it should only have one responsibility or function.
For instance, consider a Report class. If this class handles generating the report and also saving it to a file, it violates SRP. Changes to the file-saving logic could unexpectedly affect the report generation.
To follow SRP, split responsibilities into separate classes:
class Report {
public String generateReport() {
return "Report Content";
}
}
class ReportSaver {
public void saveToFile(String report, String filename) {
// Logic to save report to a file
}
}
Now, changes to saving logic don’t affect report generation. This makes the code easier to maintain and extend, adhering to good software design practices.

Hinterlasse einen Kommentar