Skip to content

Instantly share code, notes, and snippets.

@ervinod
Last active October 9, 2023 12:01
Show Gist options
  • Save ervinod/b75aace4acfda5bf98877ff60ff9e2ec to your computer and use it in GitHub Desktop.
Save ervinod/b75aace4acfda5bf98877ff60ff9e2ec to your computer and use it in GitHub Desktop.
single-responsibility-principle

single-responsibility-principle

Created with <3 with dartpad.dev.

/// 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