SOLID Principles
The S.O.L.I.D. Principles of Class Design
The Single Responsibility Principle
SalesOrder
. You would not want that class to save to the database, as well as export an XML-based receipt. Why? Well if later on down the road, you want to change database type (or if you want to change your XML schema), you're allowing one responsibility's changes to possibly alter another. Responsibility is the heart of this principle, so to rephrase there should never be more than one responsibility per class.
The Open Closed Principle
The Liskov Substitution Principle
The Dependency Inversion Principle
Employee
the class that needs to be able to be persisted to XML and a database. If we placed ToXML()
and ToDB()
functions in the class, we'd be violating the single responsibility principle. If we created a function that took a value that represented whether to print to XML or to DB, we'd be hard-coding a set of devices and thus be violating the open-closed principle. The best way to do this would be to:Create an abstract class (named
DataWriter
, perhaps) that can be inherited from for XML (XMLDataWriter
) or DB (DbDataWriter
) Saving, and thenEmployeeWriter
) that would expose an Output(DataWriter saveMethod)
that accepts a dependency as an argument. See how the Output
method is dependent upon the abstractions just as the output types are? The dependencies have been inverted. Now we can create new types of ways forEmployee
data to be written, perhaps via HTTP/HTTPS by creating abstractions, and without modifying any of our previous code! No rigidity--the desired outcome.