Single Responsibility Principle (srp)
#🖋️DesignPrinciples #💡OOP #💻SoftwareDevelopment
My fifth and last post on Principles is about SRP, this is the fifth of reverse order of -S-OLID principles with this blog post.
You can find my other blog posts Open-Closed Principle, Liskov Substitution Principle, Interface Segregation Principle and Dependency Inversion Principle
Background For Uncle Bob, RSP considered as the least well understood principle because of it’s inappropriate name and assumption of every module should do one thing.
1.SRP’s rae description stated as A module should have on, and only one reason to change. 2.Rephrased version by the Robert C. Martin on Clean Architecture book as A module should be responsible to one, and only one, user or stakeholders. 3.Final version is A module should be respobsible to one, and only one actor. The module on above statement described as a source file.
Why do we need Single Responsibility Principle? As described above, when a module tries to serve multiple actors when their business logic separated, it can come with a high cost of dependency. One busines logic change can directly effect another without noticing for a while. I would like to demonstrate a coding example using Swift.
//Bad SRP Practice
class SoccerPlayer {
func saveTheBall(goalkeeeper:String ) { /*find the player by string and use save method*/ }
func scoreGoal(striker:String ) { *find the player by string and use scoreGoal method*/ }
func pass() { /*find the player by string and use pass method*/ }
func tackle(defender:String ) { /*find the player by string and use tackle method*/ }
}
//Good SRP Practice
protocol Goalkeeper {
func save()
}
protocol Striker {
func score()
}
protocol Defender {
func tackle()
}
class SoccerPlayer {
func saveTheBall(goalkeeeper:Goalkeeper ) { goalkeeeper.save() }
func scoreGoal(striker:Striker ) { striker.score() }
func pass() { }
func tackle(defender:Defender ) { defender.tackle() }
}
I wanted to demonstrate an example of a superclass type of SoccerPlayer with only taking a string as a method property. That example uses a string to find a player and call save method for example for the goalkeeper. The improved solution where we have the good SRP practice our protocol for specific position is not only blocking the unexpected break on a change, it also gives us an opportunity to decouple and get rid of the cohesion.
You can find the related code document in here.