Created with <3 with dartpad.dev.
Last active
October 9, 2023 12:01
-
-
Save ervinod/b75aace4acfda5bf98877ff60ff9e2ec to your computer and use it in GitHub Desktop.
single-responsibility-principle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// Single Responsibility Principle /// | |
| /// A class should only be responsible for one thing that means | |
| /// a class should change for only one reason. | |
| void main() { | |
| final result = ResultBeforeSRP(); | |
| //final result = ResultAfterSRP(); | |
| result.checkResult(10); | |
| } | |
| /// Before (Violating SRP) | |
| class ResultBeforeSRP { | |
| checkResult(int rollNo) { | |
| bool isValidRollNo = validateRollNo(rollNo); | |
| if (isValidRollNo) { | |
| ResultModel resultModel = searchResult(); | |
| showResult(resultModel); | |
| } else { | |
| print("Invalid Roll No"); | |
| } | |
| } | |
| bool validateRollNo(int rollNo) { | |
| // validation logic | |
| return true; | |
| } | |
| // get api request | |
| ResultModel searchResult() { | |
| return ResultModel(); | |
| // return result; | |
| } | |
| //showing result on UI | |
| showResult(ResultModel result) { | |
| // show the result | |
| } | |
| } | |
| class ResultModel {} | |
| /// After applying SRP | |
| class ResultAfterSRP { | |
| checkResult(int rollNo) { | |
| bool isValidRollNo = Validator().validateRollNo(rollNo); | |
| if (isValidRollNo) { | |
| ResultModel resultModel = NetworkApiCall().searchResult(); | |
| Printing().showResult(resultModel); | |
| } else { | |
| print("Invalid Roll No"); | |
| } | |
| } | |
| } | |
| class Validator { | |
| // this fun is responsible for roll no validation | |
| bool validateRollNo(int rollNo) { | |
| return true; | |
| } | |
| } | |
| class Printing { | |
| // this class is responsible for printing | |
| showResult(ResultModel result) { | |
| // show the result | |
| } | |
| } | |
| class NetworkApiCall { | |
| // this class is responsible for fetching result | |
| ResultModel searchResult() { | |
| return ResultModel(); | |
| } | |
| } | |
| class ResultModel {} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment