113k views
4 votes
Give an example of a code and apply 1 of the 5 SOLID principles we covered.

(a) write a paragraph clarifying the change you will make and which principle is serves.

(b) provide UML representation before and after

(c) provide code before and after

(d) write your conclusion!

1 Answer

6 votes

Final answer:

A class, ReportGenerator, violating the Single Responsibility Principle by handling both reporting and database operations is refactored by moving the database operations to a separate DatabaseHandler class to adhere to SOLID principles, resulting in cleaner, more maintainable code.

Step-by-step explanation:

Applying SOLID Principles to Improve Code Quality

A key principle in object-oriented design is the Single Responsibility Principle, which states that a class should have only one reason to change. This encourages the separation of concerns, making the code more maintainable and flexible. In this example, we demonstrate applying the Single Responsibility Principle to a class that initially handles both database operations and business logic.

Initial Design Issue

The ReportGenerator class both generates reports and handles database operations, which violates the Single Responsibility Principle. This can lead to a harder to maintain and less flexible codebase.

Applying the Single Responsibility Principle

To adhere to this principle, we will separate the database operations into a separate DatabaseHandler class. This change will make the code easier to manage and adapt to future requirements.

UML Representation

Before: ReportGenerator - generateReport(), connectToDatabase(), executeDatabaseQuery()

After: ReportGenerator - generateReport()

DatabaseHandler - connectToDatabase(), executeDatabaseQuery()

Conclusion

By applying the Single Responsibility Principle, the classes are now more specialized and adhere to one of the critical SOLID principles for robust object-oriented design. This makes the code

User Hammerhead
by
7.3k points