This is an example of the open closed principle. The first file (2.non_ocp.dart) shows an example not using the principle and the second (3.using_ocp.dart) shows a refactor of it using the principle.
import 'package:flutter_test/flutter_test.dart'; | |
void main() { | |
test('should edit the original map as default', () { | |
final mockMap = {"item1": "value1"}; | |
expect(mockMap, {"item1": "value1"}); | |
removeFirstItemFromOriginalMap(mockMap); | |
expect(mockMap, {}); | |
}); | |
test('should create a new reference and shouldn\'t edit the original map', |
All the code examples from my Clean Code series are here.
Clean Code Youtube Playlist Link Click Here
Clean Code Book reference: https://amzn.to/3BVggeJ
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(const MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({Key? key}) : super(key: key); | |
// This widget is the root of your application. |
For the Dart language when we pass a List
to a function as a parameter we pass its reference by default, which means we are passing and editing the original list.
This may cause confusion because it doesn't follow the same pattern in all languages, the Solitity language is an example of how this could be the oposite as default.
In the first test of the following example we can see how this happens and in the second test we see how to avoid it by simply calling .toList()
at the end of the original List
, creating a new reference by doing this.
To open this example on dartpad, follow dartpad link
The same applies to Maps
, here are the examples: dartpad link
import 'failure.dart'; | |
class NoParams { | |
const NoParams._(); | |
} | |
const noParams = NoParams._(); | |
class NoResponse { | |
const NoResponse._(); |
// Have the function QuestionsMarks(str) take the str string parameter, which will contain single digit numbers, letters, and question marks, and check if there are exactly 3 question marks between every pair of two numbers that add up to 10. If so, then your program should return the string true, otherwise it should return the string false. If there aren't any two numbers that add up to 10 in the string, then your program should return false as well. | |
// For example: if str is "arrb6???4xxbl5???eee5" then your program should return true because there are exactly 3 question marks between 6 and 4, and 3 question marks between 5 and 5 at the end of the string. | |
// Examples | |
// Input: "aa6?9" | |
// Output: false | |
// Input: "acc?7??sss?3rr1??????5" | |
// Output: true | |
// Input: "bbb???2sa??aa?8" |