-
Notifications
You must be signed in to change notification settings - Fork 25
/
README.md
1839 lines (1382 loc) Β· 39.6 KB
/
README.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Clean Code in Dart
This repository is an adaptation of [ryanmcdermott/clean-code-javascript](https://github.com/ryanmcdermott/clean-code-javascript) for Dart language.
## Table of Contents
1. [Introduction](#introduction)
2. [Variables](#variables)
3. [Functions](#functions)
4. [Objects and Data Structures](#objects-and-data-structures)
5. [Classes](#classes)
6. [SOLID](#solid)
7. [Testing](#testing)
8. [Concurrency](#concurrency)
9. [Error Handling](#error-handling)
10. [Formatting](#formatting)
11. [Comments](#comments)
12. [Translation](#translation)
## Introduction
![Humorous image of software quality estimation as a count of how many expletives
you shout when reading code](https://www.osnews.com/images/comics/wtfm.jpg)
Software engineering principles, from Robert C. Martin's book
[_Clean Code_](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882),
adapted for Dart. This is not a style guide. It's a guide to producing readable, reusable, and refactorable software in Dart.
Not every principle herein has to be strictly followed, and even fewer will be
universally agreed upon. These are guidelines and nothing more, but they are
ones codified over many years of collective experience by the authors of
_Clean Code_.
Our craft of software engineering is just a bit over 50 years old, and we are
still learning a lot. When software architecture is as old as architecture
itself, maybe then we will have harder rules to follow. For now, let these
guidelines serve as a touchstone by which to assess the quality of the
Dart code that you and your team produce.
One more thing: knowing these won't immediately make you a better software
developer, and working with them for many years doesn't mean you won't make
mistakes. Every piece of code starts as a first draft, like wet clay getting
shaped into its final form. Finally, we chisel away the imperfections when
we review it with our peers. Don't beat yourself up for first drafts that need
improvement. Beat up the code instead!
## **Variables**
### Use meaningful and pronounceable variable names
**Bad:**
```dart
final yyyymmdstr = DateFormat('yyyy/MM/dd').format(DateTime.now());
```
**Good:**
```dart
final currentDate = DateFormat('yyyy/MM/dd').format(DateTime.now());
```
**[β¬ back to top](#table-of-contents)**
### Use the same vocabulary for the same type of variable
**Bad:**
```dart
getUserInfo();
getClientData();
getCustomerRecord();
```
**Good:**
```dart
getUser();
```
**[β¬ back to top](#table-of-contents)**
### Use searchable names
We will read more code than we will ever write. It's important that the code we
do write is readable and searchable. By _not_ naming variables that end up
being meaningful for understanding our program, we hurt our readers.
Make your names searchable.
**Bad:**
```dart
// What the heck is 32 for?
Future.delayed(Duration(minutes: 32), launch);
```
**Good:**
```dart
// Declare them as const if the value is known at compile time;
// Declare as final if the variable is assigned just once;
// Use lowerCamelCase;
// setupTimeInMinutes is int, because the type is inferred.
const setupTimeInMinutes = 32;
Future.delayed(Duration(minutes: setupTimeInMinutes), launch);
```
**[β¬ back to top](#table-of-contents)**
### Use explanatory variables
**Bad:**
```dart
const address = <String>['One Infinite Loop', 'Cupertino', '95014'];
saveCityZipCode(address[1], address[2]);
```
**Good:**
```dart
const address = <String>['One Infinite Loop', 'Cupertino', '95014'];
final city = address[1];
final zipCode = address[2];
saveCityZipCode(city, zipCode);
```
**[β¬ back to top](#table-of-contents)**
### Avoid Mental Mapping
Explicit is better than implicit.
**Bad:**
```dart
const locations = <String>['Austin', 'New York', 'San Francisco'];
locations.forEach((l) {
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
// Wait, what is `l` for again?
dispatch(l);
});
```
**Good:**
```dart
const locations = <String>['Austin', 'New York', 'San Francisco'];
locations.forEach((location) {
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
dispatch(location);
});
```
**[β¬ back to top](#table-of-contents)**
### Don't add unneeded context
If your class/object name tells you something, don't repeat that in your
variable name.
**Bad:**
```dart
final car = Car(
carMake: 'Honda',
carModel: 'Accord',
carColor: 'Blue',
);
void paintCar(Car car, String color) {
car.carColor = color;
}
```
**Good:**
```dart
final car = Car(
make: 'Honda',
model: 'Accord',
color: 'Blue',
);
void paintCar(Car car, String color) {
car.color = color;
}
```
**[β¬ back to top](#table-of-contents)**
### When possible, use default parameters instead of short circuiting or conditionals
Default parameters are often cleaner than short circuiting, however they must be const, so you cannot use them on every case.
**Bad:**
```dart
void createMicrobrewery({String? name}) {
final breweryName = name ?? 'Hipster Brew Co.';
// ...
}
```
**Good:**
```dart
void createMicrobrewery({String breweryName = 'Hipster Brew Co.'}) {
// ...
}
```
**[β¬ back to top](#table-of-contents)**
## **Functions**
### Function arguments (2 or fewer ideally)
Limiting the amount of function parameters is incredibly important because it
makes testing your function easier. Having more than three leads to a
combinatorial explosion where you have to test tons of different cases with
each separate argument.
One or two arguments is the ideal case, and three should be avoided if possible.
Anything more than that should be consolidated. Usually, if you have
more than two arguments then your function is trying to do too much. In cases
where it's not, most of the time a higher-level object will suffice as an
argument.
To make it obvious what properties the function expects, you can use named
parameters. They have a few advantages:
1. When someone looks at the function signature, it's immediately clear what
properties are being used.
2. Linters can warn you about unused properties, if they are `required`.
**Bad:**
```dart
Menu getMenu(String title, String body, String buttonText, bool cancellable) {
// ...
}
```
**Good:**
```dart
Menu getMenu({
required String title,
required String body,
required String buttonText,
required bool cancellable,
}) {
// ...
}
final menu = getMenu(
title: 'Foo',
body: 'Bar',
buttonText: 'Baz',
cancellable: true,
);
```
**[β¬ back to top](#table-of-contents)**
### Functions should do one thing
This is by far the most important rule in software engineering. When functions
do more than one thing, they are harder to compose, test, and reason about.
When you can isolate a function to just one action, it can be refactored
easily and your code will read much cleaner. If you take nothing else away from
this guide other than this, you'll be ahead of many developers.
**Bad:**
```dart
void emailClients(List<Client> clients) {
for(final client in clients) {
final clientRecord = database.lookup(client);
if (clientRecord.isActive()) {
email(client);
}
}
}
```
**Good:**
```dart
void emailActiveClients(List<Client> clients) {
clients
.where(isActiveClient)
.forEach(email);
}
bool isActiveClient(Client client) {
final clientRecord = database.lookup(client);
return clientRecord.isActive();
}
```
**[β¬ back to top](#table-of-contents)**
### Function names should say what they do
**Bad:**
```dart
void addToDate(DateTime date, int months) {
// ...
}
final currentDate = DateTime.now();
// It's hard to tell from the function name what is added
addToDate(currentDate, 1);
```
**Good:**
```dart
void addMonthsToDate(int months, DateTime date) {
// ...
}
final currentDate = DateTime.now();
addMonthsToDate(1, currentDate);
```
**[β¬ back to top](#table-of-contents)**
### Functions should only be one level of abstraction
When you have more than one level of abstraction your function is usually
doing too much. Splitting up functions leads to reusability and easier
testing.
**Bad:**
```dart
void parseBetterAlternative(String code) {
const regexes = [
// ...
];
final statements = code.split(' ');
final tokens = [];
for (final regex in regexes) {
for (final statement in statements) {
tokens.add( /* ... */ );
}
}
final ast = <Node>[];
for (final token in tokens) {
ast.add( /* ... */ );
}
for (final node in ast) {
// parse...
}
}
```
**Good:**
```dart
List<String> tokenize(String code) {
const regexes = [
// ...
];
final statements = code.split(' ');
final tokens = <String>[];
for (final regex in regexes) {
for (final statement in statements) {
tokens.add( /* ... */ );
}
}
return tokens;
}
List<Node> lexer(List<String> tokens) {
final ast = <Node>[];
for (final token in tokens) {
ast.add( /* ... */ );
}
return ast;
}
void parseBetterAlternative(String code) {
final tokens = tokenize(code);
final ast = lexer(tokens);
for (final node in ast) {
// parse...
}
}
```
**[β¬ back to top](#table-of-contents)**
### Remove duplicate code
Do your absolute best to avoid duplicate code. Duplicate code is bad because it
means that there's more than one place to alter something if you need to change
some logic.
Imagine if you run a restaurant and you keep track of your inventory: all your
tomatoes, onions, garlic, spices, etc. If you have multiple lists that
you keep this on, then all have to be updated when you serve a dish with
tomatoes in them. If you only have one list, there's only one place to update!
Oftentimes you have duplicate code because you have two or more slightly
different things, that share a lot in common, but their differences force you
to have two or more separate functions that do much of the same things. Removing
duplicate code means creating an abstraction that can handle this set of
different things with just one function/module/class.
Getting the abstraction right is critical, that's why you should follow the
SOLID principles laid out in the _Classes_ section. Bad abstractions can be
worse than duplicate code, so be careful! Having said this, if you can make
a good abstraction, do it! Don't repeat yourself, otherwise you'll find yourself
updating multiple places anytime you want to change one thing.
**Bad:**
```dart
Widget buildDeveloperCard(Developer developer) {
return CustomCard(
expectedSalary: developer.calculateExpectedSalary(),
experience: developer.getExperience(),
projectsLink: developer.getGithubLink(),
);
}
Widget buildManagerCard(Manager manager) {
return CustomCard(
expectedSalary: manager.calculateExpectedSalary(),
experience: manager.getExperience(),
projectsLink: manager.getMBAProjects(),
);
}
```
**Good:**
```dart
Widget buildEmployeeCard(Employee employee) {
String projectsLink;
if (employee is Manager) {
projectsLink = manager.getMBAProjects();
} else if (employee is Developer) {
projectsLink = developer.getGithubLink();
}
return CustomCard(
expectedSalary: employee.calculateExpectedSalary(),
experience: employee.getExperience(),
projectsLink: projectsLink,
);
}
```
**[β¬ back to top](#table-of-contents)**
### Don't use flags as function parameters
Flags tell your user that this function does more than one thing. Functions should do one thing. Split out your functions if they are following different code paths based on a boolean.
**Bad:**
```dart
void createFile(String name, bool temp) {
if (temp) {
File('./temp/${name}').create();
} else {
File(name).create();
}
}
```
**Good:**
```dart
void createFile(String name) {
File(name).create();
}
void createTempFile(String name) {
File('./temp/${name}').create();
}
```
**[β¬ back to top](#table-of-contents)**
### Avoid Side Effects (part 1)
A function produces a side effect if it does anything other than take a value in
and return another value or values. A side effect could be writing to a file,
modifying some global variable, or accidentally wiring all your money to a
stranger.
Now, you do need to have side effects in a program on occasion. Like the previous
example, you might need to write to a file. What you want to do is to
centralize where you are doing this. Don't have several functions and classes
that write to a particular file. Have one service that does it. One and only one.
The main point is to avoid common pitfalls like sharing state between objects
without any structure, using mutable data types that can be written to by anything,
and not centralizing where your side effects occur. If you can do this, you will
be happier than the vast majority of other programmers.
**Bad:**
```dart
// Global variable referenced by following function.
// If we had another function that used this name, now it'd be an array and it could break it.
dynamic name = 'Ryan McDermott';
void splitIntoFirstAndLastName() {
name = name.split(' ');
}
splitIntoFirstAndLastName();
print(name); // ['Ryan', 'McDermott'];
```
**Good:**
```dart
List<String> splitIntoFirstAndLastName(name) {
return name.split(' ');
}
final name = 'Ryan McDermott';
final newName = splitIntoFirstAndLastName(name);
print(name); // 'Ryan McDermott';
print(newName); // ['Ryan', 'McDermott'];
```
**[β¬ back to top](#table-of-contents)**
### Avoid Side Effects (part 2)
In Dart, some values are unchangeable (immutable) and some are changeable
(mutable). Objects and arrays are two kinds of mutable values so it's important
to handle them carefully when they're passed as parameters to a function. A
Dart function can change an object's properties or alter the contents of
an array which could easily cause bugs elsewhere.
Suppose there's a function that accepts an array parameter representing a
shopping cart. If the function makes a change in that shopping cart array -
by adding an item to purchase, for example - then any other function that
uses that same `cart` array will be affected by this addition. That may be
great, however it could also be bad. Let's imagine a bad situation:
The user clicks the "Purchase" button which calls a `purchase` function that
spawns a network request and sends the `cart` array to the server. Because
of a bad network connection, the `purchase` function has to keep retrying the
request. Now, what if in the meantime the user accidentally clicks an "Add to Cart"
button on an item they don't actually want before the network request begins?
If that happens and the network request begins, then that purchase function
will send the accidentally added item because the `cart` array was modified.
A great solution would be for the `addItemToCart` function to always clone the
`cart`, edit it, and return the clone. This would ensure that functions that are still
using the old shopping cart wouldn't be affected by the changes.
Two caveats to mention to this approach:
1. There might be cases where you actually want to modify the input object,
but when you adopt this programming practice you will find that those cases
are pretty rare. Most things can be refactored to have no side effects!
2. Cloning big objects can be very expensive in terms of performance. Luckily,
this isn't a big issue in practice because there are
[great libraries](https://facebook.github.io/immutable-js/) that allow
this kind of programming approach to be fast and not as memory intensive as
it would be for you to manually clone objects and arrays.
**Bad:**
```dart
void addItemToCart(List<int> cart, int item) {
cart.add(item);
}
final cart = <int>[1, 2];
addItemToCart(cart, 3);
print(cart); // [1, 2, 3]
```
**Good:**
```dart
List<int> addItemToCart(List<int> cart, int item) {
return [...cart, item];
}
final cart = <int>[1, 2];
final newCart = addItemToCart(cart, 3);
print(cart); // [1, 2]
print(newCart); // [1, 2, 3]
```
**[β¬ back to top](#table-of-contents)**
### Favor functional programming over imperative programming
Dart isn't a functional language in the way that Haskell is, but it has
a functional flavor to it. Functional languages can be cleaner and easier to test.
Favor this style of programming when you can.
**Bad:**
```dart
final programmerOutput = <Programmer>[
Programmer(name: 'Uncle Bobby', linesOfCode: 500),
Programmer(name: 'Suzie Q', linesOfCode: 1500),
Programmer(name: 'Jimmy Gosling', linesOfCode: 150),
Programmer(name: 'Gracie Hopper', linesOfCode: 1000),
];
var totalOutput = 0;
for (var i = 0; i < programmerOutput.length; i++) {
totalOutput += programmerOutput[i].linesOfCode;
}
```
**Good:**
```dart
final programmerOutput = <Programmer>[
Programmer(name: 'Uncle Bobby', linesOfCode: 500),
Programmer(name: 'Suzie Q', linesOfCode: 1500),
Programmer(name: 'Jimmy Gosling', linesOfCode: 150),
Programmer(name: 'Gracie Hopper', linesOfCode: 1000),
];
final totalOutput = programmerOutput.fold<int>(
0, (previousValue, programmer) => previousValue + programmer.linesOfCode);
```
**[β¬ back to top](#table-of-contents)**
### Encapsulate conditionals
**Bad:**
```dart
if (programmer.language == 'dart' && programmer.projectsList.isNotEmpty) {
// ...
}
```
**Good:**
```dart
bool isValidDartProgrammer(Programmer programmer) {
return programmer.language == 'dart' && programmer.projectsList.isNotEmpty;
}
if (isValidDartProgrammer(programmer)) {
// ...
}
```
**[β¬ back to top](#table-of-contents)**
### Avoid negative conditionals
**Bad:**
```dart
bool isFileNotValid(File file) {
// ...
}
if (!isFileNotValid(file)) {
// ...
}
```
**Good:**
```dart
bool isFileValid(File file) {
// ...
}
if (isFileValid(file)) {
// ...
}
```
**[β¬ back to top](#table-of-contents)**
### Avoid conditionals
This seems like an impossible task. Upon first hearing this, most people say,
"how am I supposed to do anything without an `if` statement?" The answer is that
you can use polymorphism to achieve the same task in many cases. The second
question is usually, "well that's great but why would I want to do that?" The
answer is a previous clean code concept we learned: a function should only do
one thing. When you have classes and functions that have `if` statements, you
are telling your user that your function does more than one thing. Remember,
just do one thing.
**Bad:**
```dart
class Airplane {
// ...
double getCruisingAltitude() {
switch (type) {
case '777':
return getMaxAltitude() - getPassengerCount();
case 'Air Force One':
return getMaxAltitude();
case 'Cessna':
return getMaxAltitude() - getFuelExpenditure();
}
}
}
```
**Good:**
```dart
class Airplane {
// ...
}
class Boeing777 extends Airplane {
// ...
double getCruisingAltitude() {
return getMaxAltitude() - getPassengerCount();
}
}
class AirForceOne extends Airplane {
// ...
double getCruisingAltitude() {
return getMaxAltitude();
}
}
class Cessna extends Airplane {
// ...
double getCruisingAltitude() {
return getMaxAltitude() - getFuelExpenditure();
}
}
```
**[β¬ back to top](#table-of-contents)**
### Remove dead code
Dead code is just as bad as duplicate code. There's no reason to keep it in
your codebase. If it's not being called, get rid of it! It will still be safe
in your version history if you still need it.
**Bad:**
```dart
Future<void> oldRequest(url) {
// ...
}
Future<void> newRequest(url) {
// ...
}
await newRequest();
```
**Good:**
```dart
Future<void> newRequest(url) {
// ...
}
await newRequest();
```
**[β¬ back to top](#table-of-contents)**
## **Objects and Data Structures**
### Use getters and setters only when necessary
Unlike other languages, in Dart it is recommended to use getters and setters only when there is some logic before using the attribute. If you just want to get or edit the attribute, don't use them.
**Bad:**
```dart
class BankAccount {
// "_" configure as private
int _balance;
int get balance => _balance;
set balance(int amount) => _balance = amount;
BankAccount({
int balance = 0,
}) : _balance = balance;
}
final account = BankAccount();
account.balance = 100;
```
**Good:**
```dart
class BankAccount {
int balance;
// ...
BankAccount({
this.balance = 0,
// ...
});
}
final account = BankAccount();
account.balance = 100;
```
**[β¬ back to top](#table-of-contents)**
### Use private methods and attributes when necessary
If a method or attribute has to be accessed only within the class, it must be private.
**Bad:**
```dart
class Employee {
String name;
Employee({required this.name});
}
final employee = Employee(name: 'John Doe');
print(employee.name); // John Doe
employee.name = 'Uncle Bob';
print(employee.name); // Uncle Bob
```
**Good:**
```dart
class Employee {
String _name;
Employee({required String name}) : _name = name;
}
final employee = Employee(name: 'John Doe');
print(employee.name); // Can't access outside the class.
```
**[β¬ back to top](#table-of-contents)**
## **Classes**
### Use method chaining (cascade notation)
It allows your code to be expressive, and less verbose. For that reason, I say,
use method chaining and take a look at how clean your code will be.
**Bad:**
```dart
class Car {
String make;
String model;
String color;
Car({
required this.make,
required this.model,
required this.color,
});
save() => print('$make, $model, $color');
}
final car = Car(make: 'Ford', model: 'F-150', color: 'red');
car.color = 'pink';
car.save();
```
**Good:**
```dart
class Car {
String make;
String model;
String color;
Car({
required this.make,
required this.model,
required this.color,
});
save() => print('$make, $model, $color');
}
final car = Car(make: 'Ford', model: 'F-150', color: 'red')
..color = 'pink'
..save();
```
**[β¬ back to top](#table-of-contents)**
### Prefer composition over inheritance
As stated famously in [_Design Patterns_](https://en.wikipedia.org/wiki/Design_Patterns) by the Gang of Four,
you should prefer composition over inheritance where you can. There are lots of
good reasons to use inheritance and lots of good reasons to use composition.
The main point for this maxim is that if your mind instinctively goes for
inheritance, try to think if composition could model your problem better. In some
cases it can.
You might be wondering then, "when should I use inheritance?" It
depends on your problem at hand, but this is a decent list of when inheritance
makes more sense than composition:
1. Your inheritance represents an "is-a" relationship and not a "has-a"
relationship (Human->Animal vs. User->UserDetails).
2. You can reuse code from the base classes (Humans can move like all animals).
3. You want to make global changes to derived classes by changing a base class.
(Change the caloric expenditure of all animals when they move).
**Bad:**
```dart
class Employee {
String name;
String email;
Employee({
required this.name,
required this.email,
});
// ...
}
// Bad because Employees "have" tax data. EmployeeTaxData is not a type of Employee
class EmployeeTaxData extends Employee {
String ssn;
double salary;
EmployeeTaxData({
required this.ssn,
required this.salary,
required super.name,
required super.email,
});
// ...
}
```
**Good:**
```dart
class EmployeeTaxData {
String ssn;
double salary;
EmployeeTaxData({
required this.ssn,
required this.salary,
});
// ...