Introduction:
-- In this series, I will explain the five rules of S.O.L.I.D principles in detail.
The reason these are important is so that, your code will be readable, maintainable, and testable.
Let`s start with the first principle [Single Responsibility]:
it means that the class should do one thing and should have only one reason to change.
Makes the version control easier to change, if the team changes a file they know why to change because it only has one purpose to change.
Example:
class Cashier (val itemCount: Int, val singleItemPrice: Int)
Now we want to write some functions into this class.
in this class, we will do the following functions:
- calculate the total item price.
- print invoice.
- save this invoice to the database.
data class Item(val itemCount: Int, val singleItemPrice: Int)
class TotalInvoicePrice(val items: Item){
fun calculatePrice() { /*Do some logic*/ }
fun printInvoice() { /*Do some logic*/ }
fun saveInvoiceToDatabase() { /*Do some logic*/ }
}
Understanding the code above we found it violate the concept of (SPR) because if we need to change (Print) Or (Save) logic we will change the class.
Don`t mix between business logic and printing logic.
So, we can make another two classes one for Printing and another for SavingToDatabase.
Every class will be responsible for one function.
class CalculatePrice(val items: Item){ fun calculatePrice() { /*Do some logic*/ } }
class PrintInvoice(val item: Item) { fun printInvoice() { /*Do some logic*/ } }
class SaveInvoice(val item: Item) { fun saveInvoiceToDatabase() { /*Do some logic*/ } }
Below is a full code snippet.
Happy coding 😀🎉
If you enjoyed this blog post ♥, follow✔, and let`s share the knowledge LinkedIn