Single Responsibility Principle
Single Responsibility Principle states that one class should only serve one purpose, it does not mean that each class should have only one method or property but they should all relate directly to the responsibility of the class.
When a class serves multiple responsibility/purposes then we should separate it into different classes.
Single Responsibility Principle Example
Let’s take a look at an example of how to write a piece of code that violates this principle.
class User { void createUser(Database db, User _UserData) { try { db.Add(_UserData); } catch (Exception ex) { db.LogError("An error occured: ", ex.ToString()); File.WriteAllText("\LocalErrors.txt", ex.ToString()); } } }
We notice how the createUser() method has too much responsibility. It can both create a user, log an error in the database, and log an error in a local file.
This violates the single responsibility principle.
Let’s correct it.
class User { void createUser(Database db, User _UserData) { try { db.Add(_UserData); } catch (Exception ex) { ErrorLogger.log(ex.ToString()); } } } class ErrorLogger { void static log(string error) { db.LogError("An error occured: ", error); File.WriteAllText("\LocalErrors.txt", error); } }
By separating the functionality that handles the error logging, we no longer violate the single responsibility principle. Now we have two classes that each has one responsibility; to create a user and to log an error, respectively.