SOLID principles are like the backbone of OOP, I've gone through this and made some good understanding of this and I thought to share with you all so that anyone can understand this principle at MAX.
Here is the list of SOLID principles.
There should never be more than one reason for a class to change. Basically, this means that your classes should exist for one purpose only. For example, let's say you are creating a class to represent a SourceServer. You would not want that class to fetch information from the database, as well as export the list of employees in CSV format. The question arises that if later on, down the line, you want to change the database type (or if you want to change your CSV format to some other format like semicolon or PDF format then, you're allowing one responsibility's changes to possibly alter another. Responsibility is the heart of this principle, so in other words there should never be more than one responsibility per class.
The following example is for illustrative purpose only:
class SourceServer
{
public static string Connection(Connection sourceServer)
{
//On behalf of sourceServer it'd return the connectionString
return connectionString;
}
public static void ExportToDefinedFormat(Connection connectionString)
{
//Export to CSV,semicolon,.pdf format code segment with help of connection string
}
}
Now everything looks great. It's time to remember the Single Responsibility Principle: every class should have only one responsibility. What responsibilities does this class have?
There are two responsibilities, so SRP is violated. The responsibilities described here are basically. There should be two classes for each responsibility.
(Illustrative purposes only)
class SourceServer
{
public static string Connection(Connection sourceServer) {
//On behalf of sourceServer it'd return the connectionString
return connectionString;
}
}
class ExportToFormat
{
public static void ExportToDefinedFormat(Connection connectionString)
{
//Export to CSV,semicolon,.pdf format code segment with help of connection string
}
}
class ConnectAndExport // this class is only responsible for ConnectionEstablishandExport to specified format
{
public static void ExportData(Connection sourceServerName)
{
string connectionString = SourceServer.Connection(sourceServerName);
ExportToFormat.ExportToDefinedFormat(connectionString);//To Export data from defined source,It could be from SQL,OLEDB,Excel..
}
}
-
ConnectAndExport is not aware of what is the "Connection "operation is, it is only aware of the intention.
-
ConnectAndExport is not aware of what ExportToDefinedFormat is, it is not aware of what code is there to export to the defined format. It is only aware of the purpose that the result should be exported to some format.
It's very easy to understand, especially for those who are not familiar with this principle. I hope you enjoyed this demonstration.
Enjoy Coding.