@mate_tsaava/pr-review 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3252 @@
1
+ # Clean Code concepts adapted for .NET/.NET Core
2
+
3
+ If you liked `clean-code-dotnet` project or if it helped you, please give a star :star: for this repository. That will not only help strengthen our .NET community but also improve skills about the clean code for .NET developers in around the world. Thank you very much :+1:
4
+
5
+ Check out my [blog](https://medium.com/@thangchung) or say hi on [Twitter](https://twitter.com/thangchung)!
6
+
7
+ # Table of Contents
8
+
9
+ - [Clean Code concepts adapted for .NET/.NET Core](#clean-code-concepts-adapted-for-netnet-core)
10
+ - [Table of Contents](#table-of-contents)
11
+ - [Introduction](#introduction)
12
+ - [Clean Code .NET](#clean-code-net)
13
+ - [Naming](#naming)
14
+ - [Variables](#variables)
15
+ - [Functions](#functions)
16
+ - [Objects and Data Structures](#objects-and-data-structures)
17
+ - [Classes](#classes)
18
+ - [SOLID](#solid)
19
+ - [Testing](#testing)
20
+ - [Concurrency](#concurrency)
21
+ - [Error Handling](#error-handling)
22
+ - [Formatting](#formatting)
23
+ - [Comments](#comments)
24
+ - [Other Clean Code Resources](#other-clean-code-resources)
25
+ - [Other Clean Code Lists](#other-clean-code-lists)
26
+ - [Style Guides](#style-guides)
27
+ - [Tools](#tools)
28
+ - [Cheatsheets](#cheatsheets)
29
+ - [Contributors](#contributors)
30
+ - [Backers](#backers)
31
+ - [Sponsors](#sponsors)
32
+ - [License](#license)
33
+
34
+ # Introduction
35
+
36
+ ![Humorous image of software quality estimation as a count of how many expletives you shout when reading code](http://www.osnews.com/images/comics/wtfm.jpg)
37
+
38
+ Software engineering principles, from Robert C. Martin's book [_Clean Code_](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882), adapted for .NET/.NET Core. This is not a style guide. It's a guide to producing readable, reusable, and refactorable software in .NET/.NET Core.
39
+
40
+ 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_.
41
+
42
+ Inspired from [clean-code-javascript](https://github.com/ryanmcdermott/clean-code-javascript) and [clean-code-php](https://github.com/jupeter/clean-code-php) lists.
43
+
44
+ # Clean Code .NET
45
+
46
+ ## Naming
47
+
48
+ <details>
49
+ <summary><b>Avoid using bad names</b></summary>
50
+ A good name allows the code to be used by many developers. The name should reflect what it does and give context.
51
+
52
+ **Bad:**
53
+
54
+ ```csharp
55
+ int d;
56
+ ```
57
+
58
+ **Good:**
59
+
60
+ ```csharp
61
+ int daySinceModification;
62
+ ```
63
+
64
+ **[⬆ Back to top](#table-of-contents)**
65
+
66
+ </details>
67
+
68
+ <details>
69
+ <summary><b>Avoid Misleading Names</b></summary>
70
+
71
+ Name the variable to reflect what it is used for.
72
+
73
+ **Bad:**
74
+
75
+ ```csharp
76
+ var dataFromDb = db.GetFromService().ToList();
77
+ ```
78
+
79
+ **Good:**
80
+
81
+ ```csharp
82
+ var listOfEmployee = _employeeService.GetEmployees().ToList();
83
+ ```
84
+
85
+ **[⬆ Back to top](#table-of-contents)**
86
+
87
+ </details>
88
+
89
+ <details>
90
+ <summary><b>Avoid Hungarian notation</b></summary>
91
+
92
+ Hungarian Notation restates the type which is already present in the declaration. This is pointless since modern IDEs will identify the type.
93
+
94
+ **Bad:**
95
+
96
+ ```csharp
97
+ int iCounter;
98
+ string strFullName;
99
+ DateTime dModifiedDate;
100
+ ```
101
+
102
+ **Good:**
103
+
104
+ ```csharp
105
+ int counter;
106
+ string fullName;
107
+ DateTime modifiedDate;
108
+ ```
109
+
110
+ Hungarian Notation should also not be used in paramaters.
111
+
112
+ **Bad:**
113
+
114
+ ```csharp
115
+ public bool IsShopOpen(string pDay, int pAmount)
116
+ {
117
+ // some logic
118
+ }
119
+ ```
120
+
121
+ **Good:**
122
+
123
+ ```csharp
124
+ public bool IsShopOpen(string day, int amount)
125
+ {
126
+ // some logic
127
+ }
128
+ ```
129
+
130
+ **[⬆ Back to top](#table-of-contents)**
131
+
132
+ </details>
133
+
134
+ <details>
135
+ <summary><b>Use consistent capitalization</b></summary>
136
+
137
+ Capitalization tells you a lot about your variables,
138
+ functions, etc. These rules are subjective, so your team can choose whatever
139
+ they want. The point is, no matter what you all choose, just be consistent.
140
+
141
+ **Bad:**
142
+
143
+ ```csharp
144
+ const int DAYS_IN_WEEK = 7;
145
+ const int daysInMonth = 30;
146
+
147
+ var songs = new List<string> { 'Back In Black', 'Stairway to Heaven', 'Hey Jude' };
148
+ var Artists = new List<string> { 'ACDC', 'Led Zeppelin', 'The Beatles' };
149
+
150
+ bool EraseDatabase() {}
151
+ bool Restore_database() {}
152
+
153
+ class animal {}
154
+ class Alpaca {}
155
+ ```
156
+
157
+ **Good:**
158
+
159
+ ```csharp
160
+ const int DaysInWeek = 7;
161
+ const int DaysInMonth = 30;
162
+
163
+ var songs = new List<string> { 'Back In Black', 'Stairway to Heaven', 'Hey Jude' };
164
+ var artists = new List<string> { 'ACDC', 'Led Zeppelin', 'The Beatles' };
165
+
166
+ bool EraseDatabase() {}
167
+ bool RestoreDatabase() {}
168
+
169
+ class Animal {}
170
+ class Alpaca {}
171
+ ```
172
+
173
+ **[⬆ back to top](#table-of-contents)**
174
+
175
+ </details>
176
+
177
+ <details>
178
+ <summary><b>Use pronounceable names</b></summary>
179
+
180
+ It will take time to investigate the meaning of the variables and functions when they are not pronounceable.
181
+
182
+ **Bad:**
183
+
184
+ ```csharp
185
+ public class Employee
186
+ {
187
+ public Datetime sWorkDate { get; set; } // what the heck is this
188
+ public Datetime modTime { get; set; } // same here
189
+ }
190
+ ```
191
+
192
+ **Good:**
193
+
194
+ ```csharp
195
+ public class Employee
196
+ {
197
+ public Datetime StartWorkingDate { get; set; }
198
+ public Datetime ModificationTime { get; set; }
199
+ }
200
+ ```
201
+
202
+ **[⬆ Back to top](#table-of-contents)**
203
+
204
+ </details>
205
+
206
+ <details>
207
+ <summary><b>Use Camelcase notation</b></summary>
208
+
209
+ Use [Camelcase Notation](https://en.wikipedia.org/wiki/Camel_case) for variable and method paramaters.
210
+
211
+ **Bad:**
212
+
213
+ ```csharp
214
+ var employeephone;
215
+
216
+ public double CalculateSalary(int workingdays, int workinghours)
217
+ {
218
+ // some logic
219
+ }
220
+ ```
221
+
222
+ **Good:**
223
+
224
+ ```csharp
225
+ var employeePhone;
226
+
227
+ public double CalculateSalary(int workingDays, int workingHours)
228
+ {
229
+ // some logic
230
+ }
231
+ ```
232
+
233
+ **[⬆ Back to top](#table-of-contents)**
234
+
235
+ </details>
236
+
237
+ <details>
238
+ <summary><b>Use domain name</b></summary>
239
+
240
+ People who read your code are also programmers. Naming things right will help everyone be on the same page. We don't want to take time to explain to everyone what a variable or function is for.
241
+
242
+ **Good**
243
+
244
+ ```csharp
245
+ public class SingleObject
246
+ {
247
+ // create an object of SingleObject
248
+ private static SingleObject _instance = new SingleObject();
249
+
250
+ // make the constructor private so that this class cannot be instantiated
251
+ private SingleObject() {}
252
+
253
+ // get the only object available
254
+ public static SingleObject GetInstance()
255
+ {
256
+ return _instance;
257
+ }
258
+
259
+ public string ShowMessage()
260
+ {
261
+ return "Hello World!";
262
+ }
263
+ }
264
+
265
+ public static void main(String[] args)
266
+ {
267
+ // illegal construct
268
+ // var object = new SingleObject();
269
+
270
+ // Get the only object available
271
+ var singletonObject = SingleObject.GetInstance();
272
+
273
+ // show the message
274
+ singletonObject.ShowMessage();
275
+ }
276
+ ```
277
+
278
+ **[⬆ Back to top](#table-of-contents)**
279
+
280
+ </details>
281
+
282
+ ## Variables
283
+
284
+ <details>
285
+ <summary><b>Avoid nesting too deeply and return early</b></summary>
286
+
287
+ Too many if else statements can make the code hard to follow. **Explicit is better than implicit**.
288
+
289
+ **Bad:**
290
+
291
+ ```csharp
292
+ public bool IsShopOpen(string day)
293
+ {
294
+ if (!string.IsNullOrEmpty(day))
295
+ {
296
+ day = day.ToLower();
297
+ if (day == "friday")
298
+ {
299
+ return true;
300
+ }
301
+ else if (day == "saturday")
302
+ {
303
+ return true;
304
+ }
305
+ else if (day == "sunday")
306
+ {
307
+ return true;
308
+ }
309
+ else
310
+ {
311
+ return false;
312
+ }
313
+ }
314
+ else
315
+ {
316
+ return false;
317
+ }
318
+
319
+ }
320
+ ```
321
+
322
+ **Good:**
323
+
324
+ ```csharp
325
+ public bool IsShopOpen(string day)
326
+ {
327
+ if (string.IsNullOrEmpty(day))
328
+ {
329
+ return false;
330
+ }
331
+
332
+ var openingDays = new[] { "friday", "saturday", "sunday" };
333
+ return openingDays.Any(d => d == day.ToLower());
334
+ }
335
+ ```
336
+
337
+ **Bad:**
338
+
339
+ ```csharp
340
+ public long Fibonacci(int n)
341
+ {
342
+ if (n < 50)
343
+ {
344
+ if (n != 0)
345
+ {
346
+ if (n != 1)
347
+ {
348
+ return Fibonacci(n - 1) + Fibonacci(n - 2);
349
+ }
350
+ else
351
+ {
352
+ return 1;
353
+ }
354
+ }
355
+ else
356
+ {
357
+ return 0;
358
+ }
359
+ }
360
+ else
361
+ {
362
+ throw new System.Exception("Not supported");
363
+ }
364
+ }
365
+ ```
366
+
367
+ **Good:**
368
+
369
+ ```csharp
370
+ public long Fibonacci(int n)
371
+ {
372
+ if (n == 0)
373
+ {
374
+ return 0;
375
+ }
376
+
377
+ if (n == 1)
378
+ {
379
+ return 1;
380
+ }
381
+
382
+ if (n > 50)
383
+ {
384
+ throw new System.Exception("Not supported");
385
+ }
386
+
387
+ return Fibonacci(n - 1) + Fibonacci(n - 2);
388
+ }
389
+ ```
390
+
391
+ **[⬆ back to top](#table-of-contents)**
392
+
393
+ </details>
394
+
395
+ <details>
396
+ <summary><b>Avoid mental mapping</b></summary>
397
+
398
+ Don’t force the reader of your code to translate what the variable means. **Explicit is better than implicit**.
399
+
400
+ **Bad:**
401
+
402
+ ```csharp
403
+ var l = new[] { "Austin", "New York", "San Francisco" };
404
+
405
+ for (var i = 0; i < l.Count(); i++)
406
+ {
407
+ var li = l[i];
408
+ DoStuff();
409
+ DoSomeOtherStuff();
410
+
411
+ // ...
412
+ // ...
413
+ // ...
414
+ // Wait, what is `li` for again?
415
+ Dispatch(li);
416
+ }
417
+ ```
418
+
419
+ **Good:**
420
+
421
+ ```csharp
422
+ var locations = new[] { "Austin", "New York", "San Francisco" };
423
+
424
+ foreach (var location in locations)
425
+ {
426
+ DoStuff();
427
+ DoSomeOtherStuff();
428
+
429
+ // ...
430
+ // ...
431
+ // ...
432
+ Dispatch(location);
433
+ }
434
+ ```
435
+
436
+ **[⬆ back to top](#table-of-contents)**
437
+
438
+ </details>
439
+
440
+ <details>
441
+ <summary><b>Avoid magic string</b></summary>
442
+
443
+ Magic strings are string values that are specified directly within application code that have an impact on the application’s behavior. Frequently, such strings will end up being duplicated within the system, and since they cannot automatically be updated using refactoring tools, they become a common source of bugs when changes are made to some strings but not others.
444
+
445
+ **Bad**
446
+
447
+ ```csharp
448
+ if (userRole == "Admin")
449
+ {
450
+ // logic in here
451
+ }
452
+ ```
453
+
454
+ **Good**
455
+
456
+ ```csharp
457
+ const string ADMIN_ROLE = "Admin"
458
+ if (userRole == ADMIN_ROLE)
459
+ {
460
+ // logic in here
461
+ }
462
+ ```
463
+
464
+ Using this we only have to change in centralize place and others will adapt it.
465
+
466
+ **[⬆ back to top](#table-of-contents)**
467
+
468
+ </details>
469
+
470
+ <details>
471
+ <summary><b>Don't add unneeded context</b></summary>
472
+
473
+ If your class/object name tells you something, don't repeat that in your variable name.
474
+
475
+ **Bad:**
476
+
477
+ ```csharp
478
+ public class Car
479
+ {
480
+ public string CarMake { get; set; }
481
+ public string CarModel { get; set; }
482
+ public string CarColor { get; set; }
483
+
484
+ //...
485
+ }
486
+ ```
487
+
488
+ **Good:**
489
+
490
+ ```csharp
491
+ public class Car
492
+ {
493
+ public string Make { get; set; }
494
+ public string Model { get; set; }
495
+ public string Color { get; set; }
496
+
497
+ //...
498
+ }
499
+ ```
500
+
501
+ **[⬆ back to top](#table-of-contents)**
502
+
503
+ </details>
504
+
505
+ <details>
506
+ <summary><b>Use meaningful and pronounceable variable names</b></summary>
507
+
508
+ **Bad:**
509
+
510
+ ```csharp
511
+ var ymdstr = DateTime.UtcNow.ToString("MMMM dd, yyyy");
512
+ ```
513
+
514
+ **Good:**
515
+
516
+ ```csharp
517
+ var currentDate = DateTime.UtcNow.ToString("MMMM dd, yyyy");
518
+ ```
519
+
520
+ **[⬆ Back to top](#table-of-contents)**
521
+
522
+ </details>
523
+
524
+ <details>
525
+ <summary><b>Use the same vocabulary for the same type of variable</b></summary>
526
+
527
+ **Bad:**
528
+
529
+ ```csharp
530
+ GetUserInfo();
531
+ GetUserData();
532
+ GetUserRecord();
533
+ GetUserProfile();
534
+ ```
535
+
536
+ **Good:**
537
+
538
+ ```csharp
539
+ GetUser();
540
+ ```
541
+
542
+ **[⬆ Back to top](#table-of-contents)**
543
+
544
+ </details>
545
+
546
+ <details>
547
+ <summary><b>Use searchable names (part 1)</b></summary>
548
+
549
+ 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.
550
+
551
+ **Bad:**
552
+
553
+ ```csharp
554
+ // What the heck is data for?
555
+ var data = new { Name = "John", Age = 42 };
556
+
557
+ var stream1 = new MemoryStream();
558
+ var ser1 = new DataContractJsonSerializer(typeof(object));
559
+ ser1.WriteObject(stream1, data);
560
+
561
+ stream1.Position = 0;
562
+ var sr1 = new StreamReader(stream1);
563
+ Console.Write("JSON form of Data object: ");
564
+ Console.WriteLine(sr1.ReadToEnd());
565
+ ```
566
+
567
+ **Good:**
568
+
569
+ ```csharp
570
+ var person = new Person
571
+ {
572
+ Name = "John",
573
+ Age = 42
574
+ };
575
+
576
+ var stream2 = new MemoryStream();
577
+ var ser2 = new DataContractJsonSerializer(typeof(Person));
578
+ ser2.WriteObject(stream2, data);
579
+
580
+ stream2.Position = 0;
581
+ var sr2 = new StreamReader(stream2);
582
+ Console.Write("JSON form of Data object: ");
583
+ Console.WriteLine(sr2.ReadToEnd());
584
+ ```
585
+
586
+ **[⬆ Back to top](#table-of-contents)**
587
+
588
+ </details>
589
+
590
+ <details>
591
+ <summary><b>Use searchable names (part 2)</b></summary>
592
+
593
+ **Bad:**
594
+
595
+ ```csharp
596
+ var data = new { Name = "John", Age = 42, PersonAccess = 4};
597
+
598
+ // What the heck is 4 for?
599
+ if (data.PersonAccess == 4)
600
+ {
601
+ // do edit ...
602
+ }
603
+ ```
604
+
605
+ **Good:**
606
+
607
+ ```csharp
608
+ public enum PersonAccess : int
609
+ {
610
+ ACCESS_READ = 1,
611
+ ACCESS_CREATE = 2,
612
+ ACCESS_UPDATE = 4,
613
+ ACCESS_DELETE = 8
614
+ }
615
+
616
+ var person = new Person
617
+ {
618
+ Name = "John",
619
+ Age = 42,
620
+ PersonAccess= PersonAccess.ACCESS_CREATE
621
+ };
622
+
623
+ if (person.PersonAccess == PersonAccess.ACCESS_UPDATE)
624
+ {
625
+ // do edit ...
626
+ }
627
+ ```
628
+
629
+ **[⬆ Back to top](#table-of-contents)**
630
+
631
+ </details>
632
+
633
+ <details>
634
+ <summary><b>Use explanatory variables</b></summary>
635
+
636
+ **Bad:**
637
+
638
+ ```csharp
639
+ const string Address = "One Infinite Loop, Cupertino 95014";
640
+ var cityZipCodeRegex = @"/^[^,\]+[,\\s]+(.+?)\s*(\d{5})?$/";
641
+ var matches = Regex.Matches(Address, cityZipCodeRegex);
642
+ if (matches[0].Success == true && matches[1].Success == true)
643
+ {
644
+ SaveCityZipCode(matches[0].Value, matches[1].Value);
645
+ }
646
+ ```
647
+
648
+ **Good:**
649
+
650
+ Decrease dependence on regex by naming subpatterns.
651
+
652
+ ```csharp
653
+ const string Address = "One Infinite Loop, Cupertino 95014";
654
+ var cityZipCodeWithGroupRegex = @"/^[^,\]+[,\\s]+(?<city>.+?)\s*(?<zipCode>\d{5})?$/";
655
+ var matchesWithGroup = Regex.Match(Address, cityZipCodeWithGroupRegex);
656
+ var cityGroup = matchesWithGroup.Groups["city"];
657
+ var zipCodeGroup = matchesWithGroup.Groups["zipCode"];
658
+ if(cityGroup.Success == true && zipCodeGroup.Success == true)
659
+ {
660
+ SaveCityZipCode(cityGroup.Value, zipCodeGroup.Value);
661
+ }
662
+ ```
663
+
664
+ **[⬆ back to top](#table-of-contents)**
665
+
666
+ </details>
667
+
668
+ <details>
669
+ <summary><b>Use default arguments instead of short circuiting or conditionals</b></summary>
670
+
671
+ **Not good:**
672
+
673
+ This is not good because `breweryName` can be `NULL`.
674
+
675
+ This opinion is more understandable than the previous version, but it better controls the value of the variable.
676
+
677
+ ```csharp
678
+ public void CreateMicrobrewery(string name = null)
679
+ {
680
+ var breweryName = !string.IsNullOrEmpty(name) ? name : "Hipster Brew Co.";
681
+ // ...
682
+ }
683
+ ```
684
+
685
+ **Good:**
686
+
687
+ ```csharp
688
+ public void CreateMicrobrewery(string breweryName = "Hipster Brew Co.")
689
+ {
690
+ // ...
691
+ }
692
+ ```
693
+
694
+ **[⬆ back to top](#table-of-contents)**
695
+
696
+ </details>
697
+
698
+ ## Functions
699
+
700
+ <details>
701
+ <summary><b>Avoid side effects</b></summary>
702
+
703
+ 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.
704
+
705
+ 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.
706
+
707
+ 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
708
+ than the vast majority of other programmers.
709
+
710
+ **Bad:**
711
+
712
+ ```csharp
713
+ // Global variable referenced by following function.
714
+ // If we had another function that used this name, now it'd be an array and it could break it.
715
+ var name = "Ryan McDermott";
716
+
717
+ public void SplitAndEnrichFullName()
718
+ {
719
+ var temp = name.Split(" ");
720
+ name = $"His first name is {temp[0]}, and his last name is {temp[1]}"; // side effect
721
+ }
722
+
723
+ SplitAndEnrichFullName();
724
+
725
+ Console.WriteLine(name); // His first name is Ryan, and his last name is McDermott
726
+ ```
727
+
728
+ **Good:**
729
+
730
+ ```csharp
731
+ public string SplitAndEnrichFullName(string name)
732
+ {
733
+ var temp = name.Split(" ");
734
+ return $"His first name is {temp[0]}, and his last name is {temp[1]}";
735
+ }
736
+
737
+ var name = "Ryan McDermott";
738
+ var fullName = SplitAndEnrichFullName(name);
739
+
740
+ Console.WriteLine(name); // Ryan McDermott
741
+ Console.WriteLine(fullName); // His first name is Ryan, and his last name is McDermott
742
+ ```
743
+
744
+ **[⬆ back to top](#table-of-contents)**
745
+
746
+ </details>
747
+
748
+ <details>
749
+ <summary><b>Avoid negative conditionals</b></summary>
750
+
751
+ **Bad:**
752
+
753
+ ```csharp
754
+ public bool IsDOMNodeNotPresent(string node)
755
+ {
756
+ // ...
757
+ }
758
+
759
+ if (!IsDOMNodeNotPresent(node))
760
+ {
761
+ // ...
762
+ }
763
+ ```
764
+
765
+ **Good:**
766
+
767
+ ```csharp
768
+ public bool IsDOMNodePresent(string node)
769
+ {
770
+ // ...
771
+ }
772
+
773
+ if (IsDOMNodePresent(node))
774
+ {
775
+ // ...
776
+ }
777
+ ```
778
+
779
+ **[⬆ back to top](#table-of-contents)**
780
+
781
+ </details>
782
+
783
+ <details>
784
+ <summary><b>Avoid conditionals</b></summary>
785
+
786
+ 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
787
+ 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.
788
+
789
+ **Bad:**
790
+
791
+ ```csharp
792
+ class Airplane
793
+ {
794
+ // ...
795
+
796
+ public double GetCruisingAltitude()
797
+ {
798
+ switch (_type)
799
+ {
800
+ case '777':
801
+ return GetMaxAltitude() - GetPassengerCount();
802
+ case 'Air Force One':
803
+ return GetMaxAltitude();
804
+ case 'Cessna':
805
+ return GetMaxAltitude() - GetFuelExpenditure();
806
+ }
807
+ }
808
+ }
809
+ ```
810
+
811
+ **Good:**
812
+
813
+ ```csharp
814
+ interface IAirplane
815
+ {
816
+ // ...
817
+
818
+ double GetCruisingAltitude();
819
+ }
820
+
821
+ class Boeing777 : IAirplane
822
+ {
823
+ // ...
824
+
825
+ public double GetCruisingAltitude()
826
+ {
827
+ return GetMaxAltitude() - GetPassengerCount();
828
+ }
829
+ }
830
+
831
+ class AirForceOne : IAirplane
832
+ {
833
+ // ...
834
+
835
+ public double GetCruisingAltitude()
836
+ {
837
+ return GetMaxAltitude();
838
+ }
839
+ }
840
+
841
+ class Cessna : IAirplane
842
+ {
843
+ // ...
844
+
845
+ public double GetCruisingAltitude()
846
+ {
847
+ return GetMaxAltitude() - GetFuelExpenditure();
848
+ }
849
+ }
850
+ ```
851
+
852
+ **[⬆ back to top](#table-of-contents)**
853
+
854
+ </details>
855
+
856
+ <details>
857
+ <summary><b>Avoid type-checking (part 1)</b></summary>
858
+
859
+ **Bad:**
860
+
861
+ ```csharp
862
+ public Path TravelToTexas(object vehicle)
863
+ {
864
+ if (vehicle.GetType() == typeof(Bicycle))
865
+ {
866
+ (vehicle as Bicycle).PeddleTo(new Location("texas"));
867
+ }
868
+ else if (vehicle.GetType() == typeof(Car))
869
+ {
870
+ (vehicle as Car).DriveTo(new Location("texas"));
871
+ }
872
+ }
873
+ ```
874
+
875
+ **Good:**
876
+
877
+ ```csharp
878
+ public Path TravelToTexas(Traveler vehicle)
879
+ {
880
+ vehicle.TravelTo(new Location("texas"));
881
+ }
882
+ ```
883
+
884
+ or
885
+
886
+ ```csharp
887
+ // pattern matching
888
+ public Path TravelToTexas(object vehicle)
889
+ {
890
+ if (vehicle is Bicycle bicycle)
891
+ {
892
+ bicycle.PeddleTo(new Location("texas"));
893
+ }
894
+ else if (vehicle is Car car)
895
+ {
896
+ car.DriveTo(new Location("texas"));
897
+ }
898
+ }
899
+ ```
900
+
901
+ **[⬆ back to top](#table-of-contents)**
902
+
903
+ </details>
904
+
905
+ <details>
906
+ <summary><b>Avoid type-checking (part 2)</b></summary>
907
+
908
+ **Bad:**
909
+
910
+ ```csharp
911
+ public int Combine(dynamic val1, dynamic val2)
912
+ {
913
+ int value;
914
+ if (!int.TryParse(val1, out value) || !int.TryParse(val2, out value))
915
+ {
916
+ throw new Exception('Must be of type Number');
917
+ }
918
+
919
+ return val1 + val2;
920
+ }
921
+ ```
922
+
923
+ **Good:**
924
+
925
+ ```csharp
926
+ public int Combine(int val1, int val2)
927
+ {
928
+ return val1 + val2;
929
+ }
930
+ ```
931
+
932
+ **[⬆ back to top](#table-of-contents)**
933
+
934
+ </details>
935
+
936
+ <details>
937
+ <summary><b>Avoid flags in method parameters</b></summary>
938
+
939
+ A flag indicates that the method has more than one responsibility. It is best if the method only has a single responsibility. Split the method into two if a boolean parameter adds multiple responsibilities to the method.
940
+
941
+ **Bad:**
942
+
943
+ ```csharp
944
+ public void CreateFile(string name, bool temp = false)
945
+ {
946
+ if (temp)
947
+ {
948
+ Touch("./temp/" + name);
949
+ }
950
+ else
951
+ {
952
+ Touch(name);
953
+ }
954
+ }
955
+ ```
956
+
957
+ **Good:**
958
+
959
+ ```csharp
960
+ public void CreateFile(string name)
961
+ {
962
+ Touch(name);
963
+ }
964
+
965
+ public void CreateTempFile(string name)
966
+ {
967
+ Touch("./temp/" + name);
968
+ }
969
+ ```
970
+
971
+ **[⬆ back to top](#table-of-contents)**
972
+
973
+ </details>
974
+
975
+ <details>
976
+ <summary><b>Don't write to global functions</b></summary>
977
+
978
+ Polluting globals is a bad practice in many languages because you could clash with another library and the user of your API would be none-the-wiser until they get an exception in production. Let's think about an example: what if you wanted to have configuration array.
979
+ You could write global function like `Config()`, but it could clash with another library that tried to do the same thing.
980
+
981
+ **Bad:**
982
+
983
+ ```csharp
984
+ public Dictionary<string, string> Config()
985
+ {
986
+ return new Dictionary<string,string>(){
987
+ ["foo"] = "bar"
988
+ };
989
+ }
990
+ ```
991
+
992
+ **Good:**
993
+
994
+ ```csharp
995
+ class Configuration
996
+ {
997
+ private Dictionary<string, string> _configuration;
998
+
999
+ public Configuration(Dictionary<string, string> configuration)
1000
+ {
1001
+ _configuration = configuration;
1002
+ }
1003
+
1004
+ public string[] Get(string key)
1005
+ {
1006
+ return _configuration.ContainsKey(key) ? _configuration[key] : null;
1007
+ }
1008
+ }
1009
+ ```
1010
+
1011
+ Load configuration and create instance of `Configuration` class
1012
+
1013
+ ```csharp
1014
+ var configuration = new Configuration(new Dictionary<string, string>() {
1015
+ ["foo"] = "bar"
1016
+ });
1017
+ ```
1018
+
1019
+ And now you must use instance of `Configuration` in your application.
1020
+
1021
+ **[⬆ back to top](#table-of-contents)**
1022
+
1023
+ </details>
1024
+
1025
+ <details>
1026
+ <summary><b>Don't use a Singleton pattern</b></summary>
1027
+
1028
+ Singleton is an [anti-pattern](https://en.wikipedia.org/wiki/Singleton_pattern). Paraphrased from Brian Button:
1029
+
1030
+ 1. They are generally used as a **global instance**, why is that so bad? Because **you hide the dependencies** of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a [code smell](https://en.wikipedia.org/wiki/Code_smell).
1031
+ 2. They violate the [single responsibility principle](#single-responsibility-principle-srp): by virtue of the fact that **they control their own creation and lifecycle**.
1032
+ 3. They inherently cause code to be tightly [coupled](https://en.wikipedia.org/wiki/Coupling_%28computer_programming%29). This makes faking them out under **test rather difficult** in many cases.
1033
+ 4. They carry state around for the lifetime of the application. Another hit to testing since **you can end up with a situation where tests need to be ordered** which is a big no for unit tests. Why? Because each unit test should be independent from the other.
1034
+
1035
+ There is also very good thoughts by [Misko Hevery](http://misko.hevery.com/about/) about the [root of problem](http://misko.hevery.com/2008/08/25/root-cause-of-singletons/).
1036
+
1037
+ **Bad:**
1038
+
1039
+ ```csharp
1040
+ class DBConnection
1041
+ {
1042
+ private static DBConnection _instance;
1043
+
1044
+ private DBConnection()
1045
+ {
1046
+ // ...
1047
+ }
1048
+
1049
+ public static GetInstance()
1050
+ {
1051
+ if (_instance == null)
1052
+ {
1053
+ _instance = new DBConnection();
1054
+ }
1055
+
1056
+ return _instance;
1057
+ }
1058
+
1059
+ // ...
1060
+ }
1061
+
1062
+ var singleton = DBConnection.GetInstance();
1063
+ ```
1064
+
1065
+ **Good:**
1066
+
1067
+ ```csharp
1068
+ class DBConnection
1069
+ {
1070
+ public DBConnection(IOptions<DbConnectionOption> options)
1071
+ {
1072
+ // ...
1073
+ }
1074
+
1075
+ // ...
1076
+ }
1077
+ ```
1078
+
1079
+ Create instance of `DBConnection` class and configure it with [Option pattern](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.1).
1080
+
1081
+ ```csharp
1082
+ var options = <resolve from IOC>;
1083
+ var connection = new DBConnection(options);
1084
+ ```
1085
+
1086
+ And now you must use instance of `DBConnection` in your application.
1087
+
1088
+ **[⬆ back to top](#table-of-contents)**
1089
+
1090
+ </details>
1091
+
1092
+ <details>
1093
+ <summary><b>Function arguments (2 or fewer ideally)</b></summary>
1094
+
1095
+ 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.
1096
+
1097
+ Zero arguments is the ideal case. One or two arguments is ok, and three should be avoided. 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.
1098
+
1099
+ **Bad:**
1100
+
1101
+ ```csharp
1102
+ public void CreateMenu(string title, string body, string buttonText, bool cancellable)
1103
+ {
1104
+ // ...
1105
+ }
1106
+ ```
1107
+
1108
+ **Good:**
1109
+
1110
+ ```csharp
1111
+ public class MenuConfig
1112
+ {
1113
+ public string Title { get; set; }
1114
+ public string Body { get; set; }
1115
+ public string ButtonText { get; set; }
1116
+ public bool Cancellable { get; set; }
1117
+ }
1118
+
1119
+ var config = new MenuConfig
1120
+ {
1121
+ Title = "Foo",
1122
+ Body = "Bar",
1123
+ ButtonText = "Baz",
1124
+ Cancellable = true
1125
+ };
1126
+
1127
+ public void CreateMenu(MenuConfig config)
1128
+ {
1129
+ // ...
1130
+ }
1131
+ ```
1132
+
1133
+ **[⬆ back to top](#table-of-contents)**
1134
+
1135
+ </details>
1136
+
1137
+ <details>
1138
+ <summary><b>Functions should do one thing</b></summary>
1139
+
1140
+ 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, they can be refactored easily and your code will read much
1141
+ cleaner. If you take nothing else away from this guide other than this, you'll be ahead of many developers.
1142
+
1143
+ **Bad:**
1144
+
1145
+ ```csharp
1146
+ public void SendEmailToListOfClients(string[] clients)
1147
+ {
1148
+ foreach (var client in clients)
1149
+ {
1150
+ var clientRecord = db.Find(client);
1151
+ if (clientRecord.IsActive())
1152
+ {
1153
+ Email(client);
1154
+ }
1155
+ }
1156
+ }
1157
+ ```
1158
+
1159
+ **Good:**
1160
+
1161
+ ```csharp
1162
+ public void SendEmailToListOfClients(string[] clients)
1163
+ {
1164
+ var activeClients = GetActiveClients(clients);
1165
+ // Do some logic
1166
+ }
1167
+
1168
+ public List<Client> GetActiveClients(string[] clients)
1169
+ {
1170
+ return db.Find(clients).Where(s => s.Status == "Active");
1171
+ }
1172
+ ```
1173
+
1174
+ **[⬆ back to top](#table-of-contents)**
1175
+
1176
+ </details>
1177
+
1178
+ <details>
1179
+ <summary><b>Function names should say what they do</b></summary>
1180
+
1181
+ **Bad:**
1182
+
1183
+ ```csharp
1184
+ public class Email
1185
+ {
1186
+ //...
1187
+
1188
+ public void Handle()
1189
+ {
1190
+ SendMail(this._to, this._subject, this._body);
1191
+ }
1192
+ }
1193
+
1194
+ var message = new Email(...);
1195
+ // What is this? A handle for the message? Are we writing to a file now?
1196
+ message.Handle();
1197
+ ```
1198
+
1199
+ **Good:**
1200
+
1201
+ ```csharp
1202
+ public class Email
1203
+ {
1204
+ //...
1205
+
1206
+ public void Send()
1207
+ {
1208
+ SendMail(this._to, this._subject, this._body);
1209
+ }
1210
+ }
1211
+
1212
+ var message = new Email(...);
1213
+ // Clear and obvious
1214
+ message.Send();
1215
+ ```
1216
+
1217
+ **[⬆ back to top](#table-of-contents)**
1218
+
1219
+ </details>
1220
+
1221
+ <details>
1222
+ <summary><b>Functions should only be one level of abstraction</b></summary>
1223
+
1224
+ > Not finished yet
1225
+
1226
+ 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.
1227
+
1228
+ **Bad:**
1229
+
1230
+ ```csharp
1231
+ public string ParseBetterJSAlternative(string code)
1232
+ {
1233
+ var regexes = [
1234
+ // ...
1235
+ ];
1236
+
1237
+ var statements = explode(" ", code);
1238
+ var tokens = new string[] {};
1239
+ foreach (var regex in regexes)
1240
+ {
1241
+ foreach (var statement in statements)
1242
+ {
1243
+ // ...
1244
+ }
1245
+ }
1246
+
1247
+ var ast = new string[] {};
1248
+ foreach (var token in tokens)
1249
+ {
1250
+ // lex...
1251
+ }
1252
+
1253
+ foreach (var node in ast)
1254
+ {
1255
+ // parse...
1256
+ }
1257
+ }
1258
+ ```
1259
+
1260
+ **Bad too:**
1261
+
1262
+ We have carried out some of the functionality, but the `ParseBetterJSAlternative()` function is still very complex and not testable.
1263
+
1264
+ ```csharp
1265
+ public string Tokenize(string code)
1266
+ {
1267
+ var regexes = new string[]
1268
+ {
1269
+ // ...
1270
+ };
1271
+
1272
+ var statements = explode(" ", code);
1273
+ var tokens = new string[] {};
1274
+ foreach (var regex in regexes)
1275
+ {
1276
+ foreach (var statement in statements)
1277
+ {
1278
+ tokens[] = /* ... */;
1279
+ }
1280
+ }
1281
+
1282
+ return tokens;
1283
+ }
1284
+
1285
+ public string Lexer(string[] tokens)
1286
+ {
1287
+ var ast = new string[] {};
1288
+ foreach (var token in tokens)
1289
+ {
1290
+ ast[] = /* ... */;
1291
+ }
1292
+
1293
+ return ast;
1294
+ }
1295
+
1296
+ public string ParseBetterJSAlternative(string code)
1297
+ {
1298
+ var tokens = Tokenize(code);
1299
+ var ast = Lexer(tokens);
1300
+ foreach (var node in ast)
1301
+ {
1302
+ // parse...
1303
+ }
1304
+ }
1305
+ ```
1306
+
1307
+ **Good:**
1308
+
1309
+ The best solution is move out the dependencies of `ParseBetterJSAlternative()` function.
1310
+
1311
+ ```csharp
1312
+ class Tokenizer
1313
+ {
1314
+ public string Tokenize(string code)
1315
+ {
1316
+ var regexes = new string[] {
1317
+ // ...
1318
+ };
1319
+
1320
+ var statements = explode(" ", code);
1321
+ var tokens = new string[] {};
1322
+ foreach (var regex in regexes)
1323
+ {
1324
+ foreach (var statement in statements)
1325
+ {
1326
+ tokens[] = /* ... */;
1327
+ }
1328
+ }
1329
+
1330
+ return tokens;
1331
+ }
1332
+ }
1333
+
1334
+ class Lexer
1335
+ {
1336
+ public string Lexify(string[] tokens)
1337
+ {
1338
+ var ast = new[] {};
1339
+ foreach (var token in tokens)
1340
+ {
1341
+ ast[] = /* ... */;
1342
+ }
1343
+
1344
+ return ast;
1345
+ }
1346
+ }
1347
+
1348
+ class BetterJSAlternative
1349
+ {
1350
+ private string _tokenizer;
1351
+ private string _lexer;
1352
+
1353
+ public BetterJSAlternative(Tokenizer tokenizer, Lexer lexer)
1354
+ {
1355
+ _tokenizer = tokenizer;
1356
+ _lexer = lexer;
1357
+ }
1358
+
1359
+ public string Parse(string code)
1360
+ {
1361
+ var tokens = _tokenizer.Tokenize(code);
1362
+ var ast = _lexer.Lexify(tokens);
1363
+ foreach (var node in ast)
1364
+ {
1365
+ // parse...
1366
+ }
1367
+ }
1368
+ }
1369
+ ```
1370
+
1371
+ **[⬆ back to top](#table-of-contents)**
1372
+
1373
+ </details>
1374
+
1375
+ <details>
1376
+ <summary><b>Function callers and callees should be close</b></summary>
1377
+
1378
+ If a function calls another, keep those functions vertically close in the source file. Ideally, keep the caller right above the callee. We tend to read code from top-to-bottom, like a newspaper. Because of this, make your code read that way.
1379
+
1380
+ **Bad:**
1381
+
1382
+ ```csharp
1383
+ class PerformanceReview
1384
+ {
1385
+ private readonly Employee _employee;
1386
+
1387
+ public PerformanceReview(Employee employee)
1388
+ {
1389
+ _employee = employee;
1390
+ }
1391
+
1392
+ private IEnumerable<PeersData> LookupPeers()
1393
+ {
1394
+ return db.lookup(_employee, 'peers');
1395
+ }
1396
+
1397
+ private ManagerData LookupManager()
1398
+ {
1399
+ return db.lookup(_employee, 'manager');
1400
+ }
1401
+
1402
+ private IEnumerable<PeerReviews> GetPeerReviews()
1403
+ {
1404
+ var peers = LookupPeers();
1405
+ // ...
1406
+ }
1407
+
1408
+ public PerfReviewData PerfReview()
1409
+ {
1410
+ GetPeerReviews();
1411
+ GetManagerReview();
1412
+ GetSelfReview();
1413
+ }
1414
+
1415
+ public ManagerData GetManagerReview()
1416
+ {
1417
+ var manager = LookupManager();
1418
+ }
1419
+
1420
+ public EmployeeData GetSelfReview()
1421
+ {
1422
+ // ...
1423
+ }
1424
+ }
1425
+
1426
+ var review = new PerformanceReview(employee);
1427
+ review.PerfReview();
1428
+ ```
1429
+
1430
+ **Good:**
1431
+
1432
+ ```csharp
1433
+ class PerformanceReview
1434
+ {
1435
+ private readonly Employee _employee;
1436
+
1437
+ public PerformanceReview(Employee employee)
1438
+ {
1439
+ _employee = employee;
1440
+ }
1441
+
1442
+ public PerfReviewData PerfReview()
1443
+ {
1444
+ GetPeerReviews();
1445
+ GetManagerReview();
1446
+ GetSelfReview();
1447
+ }
1448
+
1449
+ private IEnumerable<PeerReviews> GetPeerReviews()
1450
+ {
1451
+ var peers = LookupPeers();
1452
+ // ...
1453
+ }
1454
+
1455
+ private IEnumerable<PeersData> LookupPeers()
1456
+ {
1457
+ return db.lookup(_employee, 'peers');
1458
+ }
1459
+
1460
+ private ManagerData GetManagerReview()
1461
+ {
1462
+ var manager = LookupManager();
1463
+ return manager;
1464
+ }
1465
+
1466
+ private ManagerData LookupManager()
1467
+ {
1468
+ return db.lookup(_employee, 'manager');
1469
+ }
1470
+
1471
+ private EmployeeData GetSelfReview()
1472
+ {
1473
+ // ...
1474
+ }
1475
+ }
1476
+
1477
+ var review = new PerformanceReview(employee);
1478
+ review.PerfReview();
1479
+ ```
1480
+
1481
+ **[⬆ back to top](#table-of-contents)**
1482
+
1483
+ </details>
1484
+
1485
+ <details>
1486
+ <summary><b>Encapsulate conditionals</b></summary>
1487
+
1488
+ **Bad:**
1489
+
1490
+ ```csharp
1491
+ if (article.state == "published")
1492
+ {
1493
+ // ...
1494
+ }
1495
+ ```
1496
+
1497
+ **Good:**
1498
+
1499
+ ```csharp
1500
+ if (article.IsPublished())
1501
+ {
1502
+ // ...
1503
+ }
1504
+ ```
1505
+
1506
+ **[⬆ back to top](#table-of-contents)**
1507
+
1508
+ </details>
1509
+
1510
+ <details>
1511
+ <summary><b>Remove dead code</b></summary>
1512
+
1513
+ 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.
1514
+
1515
+ **Bad:**
1516
+
1517
+ ```csharp
1518
+ public void OldRequestModule(string url)
1519
+ {
1520
+ // ...
1521
+ }
1522
+
1523
+ public void NewRequestModule(string url)
1524
+ {
1525
+ // ...
1526
+ }
1527
+
1528
+ var request = NewRequestModule(requestUrl);
1529
+ InventoryTracker("apples", request, "www.inventory-awesome.io");
1530
+ ```
1531
+
1532
+ **Good:**
1533
+
1534
+ ```csharp
1535
+ public void RequestModule(string url)
1536
+ {
1537
+ // ...
1538
+ }
1539
+
1540
+ var request = RequestModule(requestUrl);
1541
+ InventoryTracker("apples", request, "www.inventory-awesome.io");
1542
+ ```
1543
+
1544
+ **[⬆ back to top](#table-of-contents)**
1545
+
1546
+ </details>
1547
+
1548
+ ## Objects and Data Structures
1549
+
1550
+ <details>
1551
+ <summary><b>Use getters and setters</b></summary>
1552
+
1553
+ In C# / VB.NET you can set `public`, `protected` and `private` keywords for methods.
1554
+ Using it, you can control properties modification on an object.
1555
+
1556
+ - When you want to do more beyond getting an object property, you don't have to look up and change every accessor in your codebase.
1557
+ - Makes adding validation simple when doing a `set`.
1558
+ - Encapsulates the internal representation.
1559
+ - Easy to add logging and error handling when getting and setting.
1560
+ - Inheriting this class, you can override default functionality.
1561
+ - You can lazy load your object's properties, let's say getting it from a server.
1562
+
1563
+ Additionally, this is part of Open/Closed principle, from object-oriented design principles.
1564
+
1565
+ **Bad:**
1566
+
1567
+ ```csharp
1568
+ class BankAccount
1569
+ {
1570
+ public double Balance = 1000;
1571
+ }
1572
+
1573
+ var bankAccount = new BankAccount();
1574
+
1575
+ // Fake buy shoes...
1576
+ bankAccount.Balance -= 100;
1577
+ ```
1578
+
1579
+ **Good:**
1580
+
1581
+ ```csharp
1582
+ class BankAccount
1583
+ {
1584
+ private double _balance = 0.0D;
1585
+
1586
+ pubic double Balance {
1587
+ get {
1588
+ return _balance;
1589
+ }
1590
+ }
1591
+
1592
+ public BankAccount(balance = 1000)
1593
+ {
1594
+ _balance = balance;
1595
+ }
1596
+
1597
+ public void WithdrawBalance(int amount)
1598
+ {
1599
+ if (amount > _balance)
1600
+ {
1601
+ throw new Exception('Amount greater than available balance.');
1602
+ }
1603
+
1604
+ _balance -= amount;
1605
+ }
1606
+
1607
+ public void DepositBalance(int amount)
1608
+ {
1609
+ _balance += amount;
1610
+ }
1611
+ }
1612
+
1613
+ var bankAccount = new BankAccount();
1614
+
1615
+ // Buy shoes...
1616
+ bankAccount.WithdrawBalance(price);
1617
+
1618
+ // Get balance
1619
+ balance = bankAccount.Balance;
1620
+ ```
1621
+
1622
+ **[⬆ back to top](#table-of-contents)**
1623
+
1624
+ </details>
1625
+
1626
+ <details>
1627
+ <summary><b>Make objects have private/protected members</b></summary>
1628
+
1629
+ **Bad:**
1630
+
1631
+ ```csharp
1632
+ class Employee
1633
+ {
1634
+ public string Name { get; set; }
1635
+
1636
+ public Employee(string name)
1637
+ {
1638
+ Name = name;
1639
+ }
1640
+ }
1641
+
1642
+ var employee = new Employee("John Doe");
1643
+ Console.WriteLine(employee.Name); // Employee name: John Doe
1644
+ ```
1645
+
1646
+ **Good:**
1647
+
1648
+ ```csharp
1649
+ class Employee
1650
+ {
1651
+ public string Name { get; }
1652
+
1653
+ public Employee(string name)
1654
+ {
1655
+ Name = name;
1656
+ }
1657
+ }
1658
+
1659
+ var employee = new Employee("John Doe");
1660
+ Console.WriteLine(employee.Name); // Employee name: John Doe
1661
+ ```
1662
+
1663
+ **[⬆ back to top](#table-of-contents)**
1664
+
1665
+ </details>
1666
+
1667
+ ## Classes
1668
+
1669
+ <details>
1670
+ <summary><b>Use method chaining</b></summary>
1671
+
1672
+ This pattern is very useful and commonly used in many libraries. It allows your code to be expressive, and less verbose.
1673
+ For that reason, use method chaining and take a look at how clean your code will be.
1674
+
1675
+ **Good:**
1676
+
1677
+ ```csharp
1678
+ public static class ListExtensions
1679
+ {
1680
+ public static List<T> FluentAdd<T>(this List<T> list, T item)
1681
+ {
1682
+ list.Add(item);
1683
+ return list;
1684
+ }
1685
+
1686
+ public static List<T> FluentClear<T>(this List<T> list)
1687
+ {
1688
+ list.Clear();
1689
+ return list;
1690
+ }
1691
+
1692
+ public static List<T> FluentForEach<T>(this List<T> list, Action<T> action)
1693
+ {
1694
+ list.ForEach(action);
1695
+ return list;
1696
+ }
1697
+
1698
+ public static List<T> FluentInsert<T>(this List<T> list, int index, T item)
1699
+ {
1700
+ list.Insert(index, item);
1701
+ return list;
1702
+ }
1703
+
1704
+ public static List<T> FluentRemoveAt<T>(this List<T> list, int index)
1705
+ {
1706
+ list.RemoveAt(index);
1707
+ return list;
1708
+ }
1709
+
1710
+ public static List<T> FluentReverse<T>(this List<T> list)
1711
+ {
1712
+ list.Reverse();
1713
+ return list;
1714
+ }
1715
+ }
1716
+
1717
+ internal static void ListFluentExtensions()
1718
+ {
1719
+ var list = new List<int>() { 1, 2, 3, 4, 5 }
1720
+ .FluentAdd(1)
1721
+ .FluentInsert(0, 0)
1722
+ .FluentRemoveAt(1)
1723
+ .FluentReverse()
1724
+ .FluentForEach(value => value.WriteLine())
1725
+ .FluentClear();
1726
+ }
1727
+ ```
1728
+
1729
+ **[⬆ back to top](#table-of-contents)**
1730
+
1731
+ </details>
1732
+
1733
+ <details>
1734
+ <summary><b>Prefer composition over inheritance</b></summary>
1735
+
1736
+ As stated famously in [_Design Patterns_](https://en.wikipedia.org/wiki/Design_Patterns) by the Gang of Four,
1737
+ 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.
1738
+
1739
+ 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.
1740
+
1741
+ You might be wondering then, "when should I use inheritance?" It
1742
+ depends on your problem at hand, but this is a decent list of when inheritance makes more sense than composition:
1743
+
1744
+ 1. Your inheritance represents an "is-a" relationship and not a "has-a" relationship (Human->Animal vs. User->UserDetails).
1745
+ 2. You can reuse code from the base classes (Humans can move like all animals).
1746
+ 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).
1747
+
1748
+ **Bad:**
1749
+
1750
+ ```csharp
1751
+ class Employee
1752
+ {
1753
+ private string Name { get; set; }
1754
+ private string Email { get; set; }
1755
+
1756
+ public Employee(string name, string email)
1757
+ {
1758
+ Name = name;
1759
+ Email = email;
1760
+ }
1761
+
1762
+ // ...
1763
+ }
1764
+
1765
+ // Bad because Employees "have" tax data.
1766
+ // EmployeeTaxData is not a type of Employee
1767
+
1768
+ class EmployeeTaxData : Employee
1769
+ {
1770
+ private string Name { get; }
1771
+ private string Email { get; }
1772
+
1773
+ public EmployeeTaxData(string name, string email, string ssn, string salary)
1774
+ {
1775
+ // ...
1776
+ }
1777
+
1778
+ // ...
1779
+ }
1780
+ ```
1781
+
1782
+ **Good:**
1783
+
1784
+ ```csharp
1785
+ class EmployeeTaxData
1786
+ {
1787
+ public string Ssn { get; }
1788
+ public string Salary { get; }
1789
+
1790
+ public EmployeeTaxData(string ssn, string salary)
1791
+ {
1792
+ Ssn = ssn;
1793
+ Salary = salary;
1794
+ }
1795
+
1796
+ // ...
1797
+ }
1798
+
1799
+ class Employee
1800
+ {
1801
+ public string Name { get; }
1802
+ public string Email { get; }
1803
+ public EmployeeTaxData TaxData { get; }
1804
+
1805
+ public Employee(string name, string email)
1806
+ {
1807
+ Name = name;
1808
+ Email = email;
1809
+ }
1810
+
1811
+ public void SetTax(string ssn, double salary)
1812
+ {
1813
+ TaxData = new EmployeeTaxData(ssn, salary);
1814
+ }
1815
+
1816
+ // ...
1817
+ }
1818
+ ```
1819
+
1820
+ **[⬆ back to top](#table-of-contents)**
1821
+
1822
+ </details>
1823
+
1824
+ ## SOLID
1825
+
1826
+ <details>
1827
+ <summary><b>What is SOLID?</b></summary>
1828
+
1829
+ **SOLID** is the mnemonic acronym introduced by Michael Feathers for the first five principles named by Robert Martin, which meant five basic principles of object-oriented programming and design.
1830
+
1831
+ - [S: Single Responsibility Principle (SRP)](#single-responsibility-principle-srp)
1832
+ - [O: Open/Closed Principle (OCP)](#openclosed-principle-ocp)
1833
+ - [L: Liskov Substitution Principle (LSP)](#liskov-substitution-principle-lsp)
1834
+ - [I: Interface Segregation Principle (ISP)](#interface-segregation-principle-isp)
1835
+ - [D: Dependency Inversion Principle (DIP)](#dependency-inversion-principle-dip)
1836
+
1837
+ </details>
1838
+
1839
+ <details>
1840
+ <summary><b>Single Responsibility Principle (SRP)</b></summary>
1841
+
1842
+ As stated in Clean Code, "There should never be more than one reason for a class to change". It's tempting to jam-pack a class with a lot of functionality, like when you can only take one suitcase on your flight. The issue with this is that your class won't be conceptually cohesive and it will give it many reasons to change. Minimizing the amount of times you need to change a class is important.
1843
+
1844
+ It's important because if too much functionality is in one class and you modify a piece of it, it can be difficult to understand how that will affect other dependent modules in your codebase.
1845
+
1846
+ **Bad:**
1847
+
1848
+ ```csharp
1849
+ class UserSettings
1850
+ {
1851
+ private User User;
1852
+
1853
+ public UserSettings(User user)
1854
+ {
1855
+ User = user;
1856
+ }
1857
+
1858
+ public void ChangeSettings(Settings settings)
1859
+ {
1860
+ if (verifyCredentials())
1861
+ {
1862
+ // ...
1863
+ }
1864
+ }
1865
+
1866
+ private bool VerifyCredentials()
1867
+ {
1868
+ // ...
1869
+ }
1870
+ }
1871
+ ```
1872
+
1873
+ **Good:**
1874
+
1875
+ ```csharp
1876
+ class UserAuth
1877
+ {
1878
+ private User User;
1879
+
1880
+ public UserAuth(User user)
1881
+ {
1882
+ User = user;
1883
+ }
1884
+
1885
+ public bool VerifyCredentials()
1886
+ {
1887
+ // ...
1888
+ }
1889
+ }
1890
+
1891
+ class UserSettings
1892
+ {
1893
+ private User User;
1894
+ private UserAuth Auth;
1895
+
1896
+ public UserSettings(User user)
1897
+ {
1898
+ User = user;
1899
+ Auth = new UserAuth(user);
1900
+ }
1901
+
1902
+ public void ChangeSettings(Settings settings)
1903
+ {
1904
+ if (Auth.VerifyCredentials())
1905
+ {
1906
+ // ...
1907
+ }
1908
+ }
1909
+ }
1910
+ ```
1911
+
1912
+ **[⬆ back to top](#table-of-contents)**
1913
+
1914
+ </details>
1915
+
1916
+ <details>
1917
+ <summary><b>Open/Closed Principle (OCP)</b></summary>
1918
+
1919
+ As stated by Bertrand Meyer, "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification." What does that mean though? This principle basically states that you should allow users to add new functionalities without changing existing code.
1920
+
1921
+ **Bad:**
1922
+
1923
+ ```csharp
1924
+ abstract class AdapterBase
1925
+ {
1926
+ protected string Name;
1927
+
1928
+ public string GetName()
1929
+ {
1930
+ return Name;
1931
+ }
1932
+ }
1933
+
1934
+ class AjaxAdapter : AdapterBase
1935
+ {
1936
+ public AjaxAdapter()
1937
+ {
1938
+ Name = "ajaxAdapter";
1939
+ }
1940
+ }
1941
+
1942
+ class NodeAdapter : AdapterBase
1943
+ {
1944
+ public NodeAdapter()
1945
+ {
1946
+ Name = "nodeAdapter";
1947
+ }
1948
+ }
1949
+
1950
+ class HttpRequester : AdapterBase
1951
+ {
1952
+ private readonly AdapterBase Adapter;
1953
+
1954
+ public HttpRequester(AdapterBase adapter)
1955
+ {
1956
+ Adapter = adapter;
1957
+ }
1958
+
1959
+ public bool Fetch(string url)
1960
+ {
1961
+ var adapterName = Adapter.GetName();
1962
+
1963
+ if (adapterName == "ajaxAdapter")
1964
+ {
1965
+ return MakeAjaxCall(url);
1966
+ }
1967
+ else if (adapterName == "httpNodeAdapter")
1968
+ {
1969
+ return MakeHttpCall(url);
1970
+ }
1971
+ }
1972
+
1973
+ private bool MakeAjaxCall(string url)
1974
+ {
1975
+ // request and return promise
1976
+ }
1977
+
1978
+ private bool MakeHttpCall(string url)
1979
+ {
1980
+ // request and return promise
1981
+ }
1982
+ }
1983
+ ```
1984
+
1985
+ **Good:**
1986
+
1987
+ ```csharp
1988
+ interface IAdapter
1989
+ {
1990
+ bool Request(string url);
1991
+ }
1992
+
1993
+ class AjaxAdapter : IAdapter
1994
+ {
1995
+ public bool Request(string url)
1996
+ {
1997
+ // request and return promise
1998
+ }
1999
+ }
2000
+
2001
+ class NodeAdapter : IAdapter
2002
+ {
2003
+ public bool Request(string url)
2004
+ {
2005
+ // request and return promise
2006
+ }
2007
+ }
2008
+
2009
+ class HttpRequester
2010
+ {
2011
+ private readonly IAdapter Adapter;
2012
+
2013
+ public HttpRequester(IAdapter adapter)
2014
+ {
2015
+ Adapter = adapter;
2016
+ }
2017
+
2018
+ public bool Fetch(string url)
2019
+ {
2020
+ return Adapter.Request(url);
2021
+ }
2022
+ }
2023
+ ```
2024
+
2025
+ **[⬆ back to top](#table-of-contents)**
2026
+
2027
+ </details>
2028
+
2029
+ <details>
2030
+ <summary><b>Liskov Substitution Principle (LSP)</b></summary>
2031
+
2032
+ This is a scary term for a very simple concept. It's formally defined as "If S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed,
2033
+ etc.)." That's an even scarier definition.
2034
+
2035
+ The best explanation for this is if you have a parent class and a child class, then the base class and child class can be used interchangeably without getting incorrect results. This might still be confusing, so let's take a look at the classic Square-Rectangle example. Mathematically, a square is a rectangle, but if you model it using the "is-a" relationship via inheritance, you quickly
2036
+ get into trouble.
2037
+
2038
+ **Bad:**
2039
+
2040
+ ```csharp
2041
+ class Rectangle
2042
+ {
2043
+ protected double Width = 0;
2044
+ protected double Height = 0;
2045
+
2046
+ public Drawable Render(double area)
2047
+ {
2048
+ // ...
2049
+ }
2050
+
2051
+ public void SetWidth(double width)
2052
+ {
2053
+ Width = width;
2054
+ }
2055
+
2056
+ public void SetHeight(double height)
2057
+ {
2058
+ Height = height;
2059
+ }
2060
+
2061
+ public double GetArea()
2062
+ {
2063
+ return Width * Height;
2064
+ }
2065
+ }
2066
+
2067
+ class Square : Rectangle
2068
+ {
2069
+ public double SetWidth(double width)
2070
+ {
2071
+ Width = Height = width;
2072
+ }
2073
+
2074
+ public double SetHeight(double height)
2075
+ {
2076
+ Width = Height = height;
2077
+ }
2078
+ }
2079
+
2080
+ Drawable RenderLargeRectangles(Rectangle rectangles)
2081
+ {
2082
+ foreach (rectangle in rectangles)
2083
+ {
2084
+ rectangle.SetWidth(4);
2085
+ rectangle.SetHeight(5);
2086
+ var area = rectangle.GetArea(); // BAD: Will return 25 for Square. Should be 20.
2087
+ rectangle.Render(area);
2088
+ }
2089
+ }
2090
+
2091
+ var rectangles = new[] { new Rectangle(), new Rectangle(), new Square() };
2092
+ RenderLargeRectangles(rectangles);
2093
+ ```
2094
+
2095
+ **Good:**
2096
+
2097
+ ```csharp
2098
+ abstract class ShapeBase
2099
+ {
2100
+ protected double Width = 0;
2101
+ protected double Height = 0;
2102
+
2103
+ abstract public double GetArea();
2104
+
2105
+ public Drawable Render(double area)
2106
+ {
2107
+ // ...
2108
+ }
2109
+ }
2110
+
2111
+ class Rectangle : ShapeBase
2112
+ {
2113
+ public void SetWidth(double width)
2114
+ {
2115
+ Width = width;
2116
+ }
2117
+
2118
+ public void SetHeight(double height)
2119
+ {
2120
+ Height = height;
2121
+ }
2122
+
2123
+ public double GetArea()
2124
+ {
2125
+ return Width * Height;
2126
+ }
2127
+ }
2128
+
2129
+ class Square : ShapeBase
2130
+ {
2131
+ private double Length = 0;
2132
+
2133
+ public double SetLength(double length)
2134
+ {
2135
+ Length = length;
2136
+ }
2137
+
2138
+ public double GetArea()
2139
+ {
2140
+ return Math.Pow(Length, 2);
2141
+ }
2142
+ }
2143
+
2144
+ Drawable RenderLargeRectangles(Rectangle rectangles)
2145
+ {
2146
+ foreach (rectangle in rectangles)
2147
+ {
2148
+ if (rectangle is Square)
2149
+ {
2150
+ rectangle.SetLength(5);
2151
+ }
2152
+ else if (rectangle is Rectangle)
2153
+ {
2154
+ rectangle.SetWidth(4);
2155
+ rectangle.SetHeight(5);
2156
+ }
2157
+
2158
+ var area = rectangle.GetArea();
2159
+ rectangle.Render(area);
2160
+ }
2161
+ }
2162
+
2163
+ var shapes = new[] { new Rectangle(), new Rectangle(), new Square() };
2164
+ RenderLargeRectangles(shapes);
2165
+ ```
2166
+
2167
+ **[⬆ back to top](#table-of-contents)**
2168
+
2169
+ </details>
2170
+
2171
+ <details>
2172
+ <summary><b>Interface Segregation Principle (ISP)</b></summary>
2173
+
2174
+ ISP states that "Clients should not be forced to depend upon interfaces that they do not use."
2175
+
2176
+ A good example to look at that demonstrates this principle is for
2177
+ classes that require large settings objects. Not requiring clients to setup huge amounts of options is beneficial, because most of the time they won't need all of the settings. Making them optional helps prevent having a "fat interface".
2178
+
2179
+ **Bad:**
2180
+
2181
+ ```csharp
2182
+ public interface IEmployee
2183
+ {
2184
+ void Work();
2185
+ void Eat();
2186
+ }
2187
+
2188
+ public class Human : IEmployee
2189
+ {
2190
+ public void Work()
2191
+ {
2192
+ // ....working
2193
+ }
2194
+
2195
+ public void Eat()
2196
+ {
2197
+ // ...... eating in lunch break
2198
+ }
2199
+ }
2200
+
2201
+ public class Robot : IEmployee
2202
+ {
2203
+ public void Work()
2204
+ {
2205
+ //.... working much more
2206
+ }
2207
+
2208
+ public void Eat()
2209
+ {
2210
+ //.... robot can't eat, but it must implement this method
2211
+ }
2212
+ }
2213
+ ```
2214
+
2215
+ **Good:**
2216
+
2217
+ Not every worker is an employee, but every employee is an worker.
2218
+
2219
+ ```csharp
2220
+ public interface IWorkable
2221
+ {
2222
+ void Work();
2223
+ }
2224
+
2225
+ public interface IFeedable
2226
+ {
2227
+ void Eat();
2228
+ }
2229
+
2230
+ public interface IEmployee : IFeedable, IWorkable
2231
+ {
2232
+ }
2233
+
2234
+ public class Human : IEmployee
2235
+ {
2236
+ public void Work()
2237
+ {
2238
+ // ....working
2239
+ }
2240
+
2241
+ public void Eat()
2242
+ {
2243
+ //.... eating in lunch break
2244
+ }
2245
+ }
2246
+
2247
+ // robot can only work
2248
+ public class Robot : IWorkable
2249
+ {
2250
+ public void Work()
2251
+ {
2252
+ // ....working
2253
+ }
2254
+ }
2255
+ ```
2256
+
2257
+ **[⬆ back to top](#table-of-contents)**
2258
+
2259
+ </details>
2260
+
2261
+ <details>
2262
+ <summary><b>Dependency Inversion Principle (DIP)</b></summary>
2263
+
2264
+ This principle states two essential things:
2265
+
2266
+ 1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
2267
+ 2. Abstractions should not depend upon details. Details should depend on abstractions.
2268
+
2269
+ This can be hard to understand at first, but if you've worked with .NET/.NET Core framework, you've seen an implementation of this principle in the form of [Dependency Injection](https://martinfowler.com/articles/injection.html) (DI). While they are not identical concepts, DIP keeps high-level modules from knowing the details of its low-level modules and setting them up.
2270
+ It can accomplish this through DI. A huge benefit of this is that it reduces the coupling between modules. Coupling is a very bad development pattern because it makes your code hard to refactor.
2271
+
2272
+ **Bad:**
2273
+
2274
+ ```csharp
2275
+ public abstract class EmployeeBase
2276
+ {
2277
+ protected virtual void Work()
2278
+ {
2279
+ // ....working
2280
+ }
2281
+ }
2282
+
2283
+ public class Human : EmployeeBase
2284
+ {
2285
+ public override void Work()
2286
+ {
2287
+ //.... working much more
2288
+ }
2289
+ }
2290
+
2291
+ public class Robot : EmployeeBase
2292
+ {
2293
+ public override void Work()
2294
+ {
2295
+ //.... working much, much more
2296
+ }
2297
+ }
2298
+
2299
+ public class Manager
2300
+ {
2301
+ private readonly Robot _robot;
2302
+ private readonly Human _human;
2303
+
2304
+ public Manager(Robot robot, Human human)
2305
+ {
2306
+ _robot = robot;
2307
+ _human = human;
2308
+ }
2309
+
2310
+ public void Manage()
2311
+ {
2312
+ _robot.Work();
2313
+ _human.Work();
2314
+ }
2315
+ }
2316
+ ```
2317
+
2318
+ **Good:**
2319
+
2320
+ ```csharp
2321
+ public interface IEmployee
2322
+ {
2323
+ void Work();
2324
+ }
2325
+
2326
+ public class Human : IEmployee
2327
+ {
2328
+ public void Work()
2329
+ {
2330
+ // ....working
2331
+ }
2332
+ }
2333
+
2334
+ public class Robot : IEmployee
2335
+ {
2336
+ public void Work()
2337
+ {
2338
+ //.... working much more
2339
+ }
2340
+ }
2341
+
2342
+ public class Manager
2343
+ {
2344
+ private readonly IEnumerable<IEmployee> _employees;
2345
+
2346
+ public Manager(IEnumerable<IEmployee> employees)
2347
+ {
2348
+ _employees = employees;
2349
+ }
2350
+
2351
+ public void Manage()
2352
+ {
2353
+ foreach (var employee in _employees)
2354
+ {
2355
+ _employee.Work();
2356
+ }
2357
+ }
2358
+ }
2359
+ ```
2360
+
2361
+ **[⬆ back to top](#table-of-contents)**
2362
+
2363
+ </details>
2364
+
2365
+ <details>
2366
+ <summary><b>Don’t repeat yourself (DRY)</b></summary>
2367
+
2368
+ Try to observe the [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) principle.
2369
+
2370
+ 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.
2371
+
2372
+ 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!
2373
+
2374
+ 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.
2375
+
2376
+ Getting the abstraction right is critical, that's why you should follow the SOLID principles laid out in the [Classes](#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.
2377
+
2378
+ **Bad:**
2379
+
2380
+ ```csharp
2381
+ public List<EmployeeData> ShowDeveloperList(Developers developers)
2382
+ {
2383
+ foreach (var developers in developer)
2384
+ {
2385
+ var expectedSalary = developer.CalculateExpectedSalary();
2386
+ var experience = developer.GetExperience();
2387
+ var githubLink = developer.GetGithubLink();
2388
+ var data = new[] {
2389
+ expectedSalary,
2390
+ experience,
2391
+ githubLink
2392
+ };
2393
+
2394
+ Render(data);
2395
+ }
2396
+ }
2397
+
2398
+ public List<ManagerData> ShowManagerList(Manager managers)
2399
+ {
2400
+ foreach (var manager in managers)
2401
+ {
2402
+ var expectedSalary = manager.CalculateExpectedSalary();
2403
+ var experience = manager.GetExperience();
2404
+ var githubLink = manager.GetGithubLink();
2405
+ var data =
2406
+ new[] {
2407
+ expectedSalary,
2408
+ experience,
2409
+ githubLink
2410
+ };
2411
+
2412
+ render(data);
2413
+ }
2414
+ }
2415
+ ```
2416
+
2417
+ **Good:**
2418
+
2419
+ ```csharp
2420
+ public List<EmployeeData> ShowList(Employee employees)
2421
+ {
2422
+ foreach (var employee in employees)
2423
+ {
2424
+ var expectedSalary = employees.CalculateExpectedSalary();
2425
+ var experience = employees.GetExperience();
2426
+ var githubLink = employees.GetGithubLink();
2427
+ var data =
2428
+ new[] {
2429
+ expectedSalary,
2430
+ experience,
2431
+ githubLink
2432
+ };
2433
+
2434
+ render(data);
2435
+ }
2436
+ }
2437
+ ```
2438
+
2439
+ **Very good:**
2440
+
2441
+ It is better to use a compact version of the code.
2442
+
2443
+ ```csharp
2444
+ public List<EmployeeData> ShowList(Employee employees)
2445
+ {
2446
+ foreach (var employee in employees)
2447
+ {
2448
+ render(new[] {
2449
+ employee.CalculateExpectedSalary(),
2450
+ employee.GetExperience(),
2451
+ employee.GetGithubLink()
2452
+ });
2453
+ }
2454
+ }
2455
+ ```
2456
+
2457
+ **[⬆ back to top](#table-of-contents)**
2458
+
2459
+ </details>
2460
+
2461
+ ## Testing
2462
+
2463
+ <details>
2464
+ <summary><b>Basic concept of testing</b></summary>
2465
+
2466
+ Testing is more important than shipping. If you have no tests or an
2467
+ inadequate amount, then every time you ship code you won't be sure that you didn't break anything. Deciding on what constitutes an adequate amount is up to your team, but having 100% coverage (all statements and branches) is how you achieve very high confidence and developer peace of mind. This means that in addition to having a great testing framework, you also need to use a [good coverage tool](https://docs.microsoft.com/en-us/visualstudio/test/using-code-coverage-to-determine-how-much-code-is-being-tested).
2468
+
2469
+ There's no excuse to not write tests. There's [plenty of good .NET test frameworks](https://github.com/thangchung/awesome-dotnet-core#testing), so find one that your team prefers. When you find one that works for your team, then aim to always write tests for every new feature/module you introduce. If your preferred method is Test Driven Development (TDD), that is great, but the main point is to just make sure you are reaching your coverage goals before launching any feature, or refactoring an existing one.
2470
+
2471
+ </details>
2472
+
2473
+ <details>
2474
+ <summary><b>Single concept per test</b></summary>
2475
+
2476
+ Ensures that your tests are laser focused and not testing miscellaenous (non-related) things, forces [AAA patern](http://wiki.c2.com/?ArrangeActAssert) used to make your codes more clean and readable.
2477
+
2478
+ **Bad:**
2479
+
2480
+ ```csharp
2481
+
2482
+ public class MakeDotNetGreatAgainTests
2483
+ {
2484
+ [Fact]
2485
+ public void HandleDateBoundaries()
2486
+ {
2487
+ var date = new MyDateTime("1/1/2015");
2488
+ date.AddDays(30);
2489
+ Assert.Equal("1/31/2015", date);
2490
+
2491
+ date = new MyDateTime("2/1/2016");
2492
+ date.AddDays(28);
2493
+ Assert.Equal("02/29/2016", date);
2494
+
2495
+ date = new MyDateTime("2/1/2015");
2496
+ date.AddDays(28);
2497
+ Assert.Equal("03/01/2015", date);
2498
+ }
2499
+ }
2500
+
2501
+ ```
2502
+
2503
+ **Good:**
2504
+
2505
+ ```csharp
2506
+
2507
+ public class MakeDotNetGreatAgainTests
2508
+ {
2509
+ [Fact]
2510
+ public void Handle30DayMonths()
2511
+ {
2512
+ // Arrange
2513
+ var date = new MyDateTime("1/1/2015");
2514
+
2515
+ // Act
2516
+ date.AddDays(30);
2517
+
2518
+ // Assert
2519
+ Assert.Equal("1/31/2015", date);
2520
+ }
2521
+
2522
+ [Fact]
2523
+ public void HandleLeapYear()
2524
+ {
2525
+ // Arrange
2526
+ var date = new MyDateTime("2/1/2016");
2527
+
2528
+ // Act
2529
+ date.AddDays(28);
2530
+
2531
+ // Assert
2532
+ Assert.Equal("02/29/2016", date);
2533
+ }
2534
+
2535
+ [Fact]
2536
+ public void HandleNonLeapYear()
2537
+ {
2538
+ // Arrange
2539
+ var date = new MyDateTime("2/1/2015");
2540
+
2541
+ // Act
2542
+ date.AddDays(28);
2543
+
2544
+ // Assert
2545
+ Assert.Equal("03/01/2015", date);
2546
+ }
2547
+ }
2548
+
2549
+ ```
2550
+
2551
+ > Soure https://www.codingblocks.net/podcast/how-to-write-amazing-unit-tests
2552
+
2553
+ **[⬆ back to top](#table-of-contents)**
2554
+
2555
+ </details>
2556
+
2557
+ ## Concurrency
2558
+
2559
+ <details>
2560
+ <summary><b>Use Async/Await</b></summary>
2561
+
2562
+ **Summary of Asynchronous Programming Guidelines**
2563
+
2564
+ | Name | Description | Exceptions |
2565
+ | ----------------- | ------------------------------------------------- | ------------------------------- |
2566
+ | Avoid async void | Prefer async Task methods over async void methods | Event handlers |
2567
+ | Async all the way | Don't mix blocking and async code | Console main method (C# <= 7.0) |
2568
+ | Configure context | Use `ConfigureAwait(false)` when you can | Methods that require con­text |
2569
+
2570
+ **The Async Way of Doing Things**
2571
+
2572
+ | To Do This ... | Instead of This ... | Use This |
2573
+ | ---------------------------------------- | -------------------------- | -------------------- |
2574
+ | Retrieve the result of a background task | `Task.Wait or Task.Result` | `await` |
2575
+ | Wait for any task to complete | `Task.WaitAny` | `await Task.WhenAny` |
2576
+ | Retrieve the results of multiple tasks | `Task.WaitAll` | `await Task.WhenAll` |
2577
+ | Wait a period of time | `Thread.Sleep` | `await Task.Delay` |
2578
+
2579
+ **Best practice**
2580
+
2581
+ The async/await is the best for IO bound tasks (networking communication, database communication, http request, etc.) but it is not good to apply on computational bound tasks (traverse on the huge list, render a hugge image, etc.). Because it will release the holding thread to the thread pool and CPU/cores available will not involve to process those tasks. Therefore, we should avoid using Async/Await for computional bound tasks.
2582
+
2583
+ For dealing with computational bound tasks, prefer to use `Task.Factory.CreateNew` with `TaskCreationOptions` is `LongRunning`. It will start a new background thread to process a heavy computational bound task without release it back to the thread pool until the task being completed.
2584
+
2585
+ **Know Your Tools**
2586
+
2587
+ There's a lot to learn about async and await, and it's natural to get a little disoriented. Here's a quick reference of solutions to common problems.
2588
+
2589
+ **Solutions to Common Async Problems**
2590
+
2591
+ | Problem | Solution |
2592
+ | ----------------------------------------------- | --------------------------------------------------------------------------------- |
2593
+ | Create a task to execute code | `Task.Run` or `TaskFactory.StartNew` (not the `Task` constructor or `Task.Start`) |
2594
+ | Create a task wrapper for an operation or event | `TaskFactory.FromAsync` or `TaskCompletionSource<T>` |
2595
+ | Support cancellation | `CancellationTokenSource` and `CancellationToken` |
2596
+ | Report progress | `IProgress<T>` and `Progress<T>` |
2597
+ | Handle streams of data | TPL Dataflow or Reactive Extensions |
2598
+ | Synchronize access to a shared resource | `SemaphoreSlim` |
2599
+ | Asynchronously initialize a resource | `AsyncLazy<T>` |
2600
+ | Async-ready producer/consumer structures | TPL Dataflow or `AsyncCollection<T>` |
2601
+
2602
+ Read the [Task-based Asynchronous Pattern (TAP) document](http://www.microsoft.com/download/en/details.aspx?id=19957).
2603
+ It is extremely well-written, and includes guidance on API design and the proper use of async/await (including cancellation and progress reporting).
2604
+
2605
+ There are many new await-friendly techniques that should be used instead of the old blocking techniques. If you have any of these Old examples in your new async code, you're Doing It Wrong(TM):
2606
+
2607
+ | Old | New | Description |
2608
+ | ------------------ | ------------------------------------ | ------------------------------------------------------------- |
2609
+ | `task.Wait` | `await task` | Wait/await for a task to complete |
2610
+ | `task.Result` | `await task` | Get the result of a completed task |
2611
+ | `Task.WaitAny` | `await Task.WhenAny` | Wait/await for one of a collection of tasks to complete |
2612
+ | `Task.WaitAll` | `await Task.WhenAll` | Wait/await for every one of a collection of tasks to complete |
2613
+ | `Thread.Sleep` | `await Task.Delay` | Wait/await for a period of time |
2614
+ | `Task` constructor | `Task.Run` or `TaskFactory.StartNew` | Create a code-based task |
2615
+
2616
+ > Source https://gist.github.com/jonlabelle/841146854b23b305b50fa5542f84b20c
2617
+
2618
+ **[⬆ back to top](#table-of-contents)**
2619
+
2620
+ </details>
2621
+
2622
+ ## Error Handling
2623
+
2624
+ <details>
2625
+ <summary><b>Basic concept of error handling</b></summary>
2626
+
2627
+ Thrown errors are a good thing! They mean the runtime has successfully identified when something in your program has gone wrong and it's letting you know by stopping function execution on the current stack, killing the process (in .NET/.NET Core), and notifying you in the console with a stack trace.
2628
+
2629
+ </details>
2630
+
2631
+ <details>
2632
+ <summary><b>Don't use 'throw ex' in catch block</b></summary>
2633
+
2634
+ If you need to re-throw an exception after catching it, use just 'throw'
2635
+ By using this, you will save the stack trace. But in the bad option below,
2636
+ you will lost the stack trace.
2637
+
2638
+ **Bad:**
2639
+
2640
+ ```csharp
2641
+ try
2642
+ {
2643
+ // Do something..
2644
+ }
2645
+ catch (Exception ex)
2646
+ {
2647
+ // Any action something like roll-back or logging etc.
2648
+ throw ex;
2649
+ }
2650
+ ```
2651
+
2652
+ **Good:**
2653
+
2654
+ ```csharp
2655
+ try
2656
+ {
2657
+ // Do something..
2658
+ }
2659
+ catch (Exception ex)
2660
+ {
2661
+ // Any action something like roll-back or logging etc.
2662
+ throw;
2663
+ }
2664
+ ```
2665
+
2666
+ **[⬆ back to top](#table-of-contents)**
2667
+
2668
+ </details>
2669
+
2670
+ <details>
2671
+ <summary><b>Don't ignore caught errors</b></summary>
2672
+
2673
+ Doing nothing with a caught error doesn't give you the ability to ever fix or react to said error. Throwing the error isn't much better as often times it can get lost in a sea of things printed to the console. If you wrap any bit of code in a `try/catch` it means you think an error may occur there and therefore you should have a plan, or create a code path, for when it occurs.
2674
+
2675
+ **Bad:**
2676
+
2677
+ ```csharp
2678
+ try
2679
+ {
2680
+ FunctionThatMightThrow();
2681
+ }
2682
+ catch (Exception ex)
2683
+ {
2684
+ // silent exception
2685
+ }
2686
+ ```
2687
+
2688
+ **Good:**
2689
+
2690
+ ```csharp
2691
+ try
2692
+ {
2693
+ FunctionThatMightThrow();
2694
+ }
2695
+ catch (Exception error)
2696
+ {
2697
+ NotifyUserOfError(error);
2698
+
2699
+ // Another option
2700
+ ReportErrorToService(error);
2701
+ }
2702
+ ```
2703
+
2704
+ **[⬆ back to top](#table-of-contents)**
2705
+
2706
+ </details>
2707
+
2708
+ <details>
2709
+ <summary><b>Use multiple catch block instead of if conditions.</b></summary>
2710
+
2711
+ If you need to take action according to type of the exception,
2712
+ you better use multiple catch block for exception handling.
2713
+
2714
+ **Bad:**
2715
+
2716
+ ```csharp
2717
+ try
2718
+ {
2719
+ // Do something..
2720
+ }
2721
+ catch (Exception ex)
2722
+ {
2723
+
2724
+ if (ex is TaskCanceledException)
2725
+ {
2726
+ // Take action for TaskCanceledException
2727
+ }
2728
+ else if (ex is TaskSchedulerException)
2729
+ {
2730
+ // Take action for TaskSchedulerException
2731
+ }
2732
+ }
2733
+ ```
2734
+
2735
+ **Good:**
2736
+
2737
+ ```csharp
2738
+ try
2739
+ {
2740
+ // Do something..
2741
+ }
2742
+ catch (TaskCanceledException ex)
2743
+ {
2744
+ // Take action for TaskCanceledException
2745
+ }
2746
+ catch (TaskSchedulerException ex)
2747
+ {
2748
+ // Take action for TaskSchedulerException
2749
+ }
2750
+ ```
2751
+
2752
+ **[⬆ back to top](#table-of-contents)**
2753
+
2754
+ </details>
2755
+
2756
+ <details>
2757
+ <summary><b>Keep exception stack trace when rethrowing exceptions</b></summary>
2758
+
2759
+ C# allows the exception to be rethrown in a catch block using the `throw` keyword. It is a bad practice to throw a caught exception using `throw e;`. This statement resets the stack trace. Instead use `throw;`. This will keep the stack trace and provide a deeper insight about the exception.
2760
+ Another option is to use a custom exception. Simply instantiate a new exception and set its inner exception property to the caught exception with throw `new CustomException("some info", e);`. Adding information to an exception is a good practice as it will help with debugging. However, if the objective is to log an exception then use `throw;` to pass the buck to the caller.
2761
+
2762
+ **Bad:**
2763
+
2764
+ ```csharp
2765
+ try
2766
+ {
2767
+ FunctionThatMightThrow();
2768
+ }
2769
+ catch (Exception ex)
2770
+ {
2771
+ logger.LogInfo(ex);
2772
+ throw ex;
2773
+ }
2774
+ ```
2775
+
2776
+ **Good:**
2777
+
2778
+ ```csharp
2779
+ try
2780
+ {
2781
+ FunctionThatMightThrow();
2782
+ }
2783
+ catch (Exception error)
2784
+ {
2785
+ logger.LogInfo(error);
2786
+ throw;
2787
+ }
2788
+ ```
2789
+
2790
+ **Good:**
2791
+
2792
+ ```csharp
2793
+ try
2794
+ {
2795
+ FunctionThatMightThrow();
2796
+ }
2797
+ catch (Exception error)
2798
+ {
2799
+ logger.LogInfo(error);
2800
+ throw new CustomException(error);
2801
+ }
2802
+ ```
2803
+
2804
+ **[⬆ back to top](#table-of-contents)**
2805
+
2806
+ </details>
2807
+
2808
+ ## Formatting
2809
+
2810
+ <details>
2811
+ <summary><b>Uses <i>.editorconfig</i> file</b></summary>
2812
+
2813
+ **Bad:**
2814
+
2815
+ Has many code formatting styles in the project. For example, indent style is `space` and `tab` mixed in the project.
2816
+
2817
+ **Good:**
2818
+
2819
+ Define and maintain consistent code style in your codebase with the use of an `.editorconfig` file
2820
+
2821
+ ```csharp
2822
+ root = true
2823
+
2824
+ [*]
2825
+ indent_style = space
2826
+ indent_size = 2
2827
+ end_of_line = lf
2828
+ charset = utf-8
2829
+ trim_trailing_whitespace = true
2830
+ insert_final_newline = true
2831
+
2832
+ # C# files
2833
+ [*.cs]
2834
+ indent_size = 4
2835
+ # New line preferences
2836
+ csharp_new_line_before_open_brace = all
2837
+ csharp_new_line_before_else = true
2838
+ csharp_new_line_before_catch = true
2839
+ csharp_new_line_before_finally = true
2840
+ csharp_new_line_before_members_in_object_initializers = true
2841
+ csharp_new_line_before_members_in_anonymous_types = true
2842
+ csharp_new_line_within_query_expression_clauses = true
2843
+
2844
+ # Code files
2845
+ [*.{cs,csx,vb,vbx}]
2846
+ indent_size = 4
2847
+
2848
+ # Indentation preferences
2849
+ csharp_indent_block_contents = true
2850
+ csharp_indent_braces = false
2851
+ csharp_indent_case_contents = true
2852
+ csharp_indent_switch_labels = true
2853
+ csharp_indent_labels = one_less_than_current
2854
+
2855
+ # avoid this. unless absolutely necessary
2856
+ dotnet_style_qualification_for_field = false:suggestion
2857
+ dotnet_style_qualification_for_property = false:suggestion
2858
+ dotnet_style_qualification_for_method = false:suggestion
2859
+ dotnet_style_qualification_for_event = false:suggestion
2860
+
2861
+ # only use var when it's obvious what the variable type is
2862
+ # csharp_style_var_for_built_in_types = false:none
2863
+ # csharp_style_var_when_type_is_apparent = false:none
2864
+ # csharp_style_var_elsewhere = false:suggestion
2865
+
2866
+ # use language keywords instead of BCL types
2867
+ dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
2868
+ dotnet_style_predefined_type_for_member_access = true:suggestion
2869
+
2870
+ # name all constant fields using PascalCase
2871
+ dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion
2872
+ dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields
2873
+ dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style
2874
+
2875
+ dotnet_naming_symbols.constant_fields.applicable_kinds = field
2876
+ dotnet_naming_symbols.constant_fields.required_modifiers = const
2877
+
2878
+ dotnet_naming_style.pascal_case_style.capitalization = pascal_case
2879
+
2880
+ # static fields should have s_ prefix
2881
+ dotnet_naming_rule.static_fields_should_have_prefix.severity = suggestion
2882
+ dotnet_naming_rule.static_fields_should_have_prefix.symbols = static_fields
2883
+ dotnet_naming_rule.static_fields_should_have_prefix.style = static_prefix_style
2884
+
2885
+ dotnet_naming_symbols.static_fields.applicable_kinds = field
2886
+ dotnet_naming_symbols.static_fields.required_modifiers = static
2887
+
2888
+ dotnet_naming_style.static_prefix_style.required_prefix = s_
2889
+ dotnet_naming_style.static_prefix_style.capitalization = camel_case
2890
+
2891
+ # internal and private fields should be _camelCase
2892
+ dotnet_naming_rule.camel_case_for_private_internal_fields.severity = suggestion
2893
+ dotnet_naming_rule.camel_case_for_private_internal_fields.symbols = private_internal_fields
2894
+ dotnet_naming_rule.camel_case_for_private_internal_fields.style = camel_case_underscore_style
2895
+
2896
+ dotnet_naming_symbols.private_internal_fields.applicable_kinds = field
2897
+ dotnet_naming_symbols.private_internal_fields.applicable_accessibilities = private, internal
2898
+
2899
+ dotnet_naming_style.camel_case_underscore_style.required_prefix = _
2900
+ dotnet_naming_style.camel_case_underscore_style.capitalization = camel_case
2901
+
2902
+ # Code style defaults
2903
+ dotnet_sort_system_directives_first = true
2904
+ csharp_preserve_single_line_blocks = true
2905
+ csharp_preserve_single_line_statements = false
2906
+
2907
+ # Expression-level preferences
2908
+ dotnet_style_object_initializer = true:suggestion
2909
+ dotnet_style_collection_initializer = true:suggestion
2910
+ dotnet_style_explicit_tuple_names = true:suggestion
2911
+ dotnet_style_coalesce_expression = true:suggestion
2912
+ dotnet_style_null_propagation = true:suggestion
2913
+
2914
+ # Expression-bodied members
2915
+ csharp_style_expression_bodied_methods = false:none
2916
+ csharp_style_expression_bodied_constructors = false:none
2917
+ csharp_style_expression_bodied_operators = false:none
2918
+ csharp_style_expression_bodied_properties = true:none
2919
+ csharp_style_expression_bodied_indexers = true:none
2920
+ csharp_style_expression_bodied_accessors = true:none
2921
+
2922
+ # Pattern matching
2923
+ csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
2924
+ csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
2925
+ csharp_style_inlined_variable_declaration = true:suggestion
2926
+
2927
+ # Null checking preferences
2928
+ csharp_style_throw_expression = true:suggestion
2929
+ csharp_style_conditional_delegate_call = true:suggestion
2930
+
2931
+ # Space preferences
2932
+ csharp_space_after_cast = false
2933
+ csharp_space_after_colon_in_inheritance_clause = true
2934
+ csharp_space_after_comma = true
2935
+ csharp_space_after_dot = false
2936
+ csharp_space_after_keywords_in_control_flow_statements = true
2937
+ csharp_space_after_semicolon_in_for_statement = true
2938
+ csharp_space_around_binary_operators = before_and_after
2939
+ csharp_space_around_declaration_statements = do_not_ignore
2940
+ csharp_space_before_colon_in_inheritance_clause = true
2941
+ csharp_space_before_comma = false
2942
+ csharp_space_before_dot = false
2943
+ csharp_space_before_open_square_brackets = false
2944
+ csharp_space_before_semicolon_in_for_statement = false
2945
+ csharp_space_between_empty_square_brackets = false
2946
+ csharp_space_between_method_call_empty_parameter_list_parentheses = false
2947
+ csharp_space_between_method_call_name_and_opening_parenthesis = false
2948
+ csharp_space_between_method_call_parameter_list_parentheses = false
2949
+ csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
2950
+ csharp_space_between_method_declaration_name_and_open_parenthesis = false
2951
+ csharp_space_between_method_declaration_parameter_list_parentheses = false
2952
+ csharp_space_between_parentheses = false
2953
+ csharp_space_between_square_brackets = false
2954
+
2955
+ [*.{asm,inc}]
2956
+ indent_size = 8
2957
+
2958
+ # Xml project files
2959
+ [*.{csproj,vcxproj,vcxproj.filters,proj,nativeproj,locproj}]
2960
+ indent_size = 2
2961
+
2962
+ # Xml config files
2963
+ [*.{props,targets,config,nuspec}]
2964
+ indent_size = 2
2965
+
2966
+ [CMakeLists.txt]
2967
+ indent_size = 2
2968
+
2969
+ [*.cmd]
2970
+ indent_size = 2
2971
+
2972
+ ```
2973
+
2974
+ **[⬆ back to top](#table-of-contents)**
2975
+
2976
+ </details>
2977
+
2978
+ ## Comments
2979
+
2980
+ <details>
2981
+ <summary><b>Avoid positional markers</b></summary>
2982
+
2983
+ They usually just add noise. Let the functions and variable names along with the proper indentation and formatting give the visual structure to your code.
2984
+
2985
+ **Bad:**
2986
+
2987
+ ```csharp
2988
+ ////////////////////////////////////////////////////////////////////////////////
2989
+ // Scope Model Instantiation
2990
+ ////////////////////////////////////////////////////////////////////////////////
2991
+ var model = new[]
2992
+ {
2993
+ menu: 'foo',
2994
+ nav: 'bar'
2995
+ };
2996
+
2997
+ ////////////////////////////////////////////////////////////////////////////////
2998
+ // Action setup
2999
+ ////////////////////////////////////////////////////////////////////////////////
3000
+ void Actions()
3001
+ {
3002
+ // ...
3003
+ };
3004
+ ```
3005
+
3006
+ **Bad:**
3007
+
3008
+ ```csharp
3009
+
3010
+ #region Scope Model Instantiation
3011
+
3012
+ var model = {
3013
+ menu: 'foo',
3014
+ nav: 'bar'
3015
+ };
3016
+
3017
+ #endregion
3018
+
3019
+ #region Action setup
3020
+
3021
+ void Actions() {
3022
+ // ...
3023
+ };
3024
+
3025
+ #endregion
3026
+ ```
3027
+
3028
+ **Good:**
3029
+
3030
+ ```csharp
3031
+ var model = new[]
3032
+ {
3033
+ menu: 'foo',
3034
+ nav: 'bar'
3035
+ };
3036
+
3037
+ void Actions()
3038
+ {
3039
+ // ...
3040
+ };
3041
+ ```
3042
+
3043
+ **[⬆ back to top](#table-of-contents)**
3044
+
3045
+ </details>
3046
+
3047
+ <details>
3048
+ <summary><b>Don't leave commented out code in your codebase</b></summary>
3049
+
3050
+ Version control exists for a reason. Leave old code in your history.
3051
+
3052
+ **Bad:**
3053
+
3054
+ ```csharp
3055
+ doStuff();
3056
+ // doOtherStuff();
3057
+ // doSomeMoreStuff();
3058
+ // doSoMuchStuff();
3059
+ ```
3060
+
3061
+ **Good:**
3062
+
3063
+ ```csharp
3064
+ doStuff();
3065
+ ```
3066
+
3067
+ **[⬆ back to top](#table-of-contents)**
3068
+
3069
+ </details>
3070
+
3071
+ <details>
3072
+ <summary><b>Don't have journal comments</b></summary>
3073
+
3074
+ Remember, use version control! There's no need for dead code, commented code, and especially journal comments. Use `git log` to get history!
3075
+
3076
+ **Bad:**
3077
+
3078
+ ```csharp
3079
+ /**
3080
+ * 2018-12-20: Removed monads, didn't understand them (RM)
3081
+ * 2017-10-01: Improved using special monads (JP)
3082
+ * 2016-02-03: Removed type-checking (LI)
3083
+ * 2015-03-14: Added combine with type-checking (JR)
3084
+ */
3085
+ public int Combine(int a,int b)
3086
+ {
3087
+ return a + b;
3088
+ }
3089
+ ```
3090
+
3091
+ **Good:**
3092
+
3093
+ ```csharp
3094
+ public int Combine(int a,int b)
3095
+ {
3096
+ return a + b;
3097
+ }
3098
+ ```
3099
+
3100
+ **[⬆ back to top](#table-of-contents)**
3101
+
3102
+ </details>
3103
+
3104
+ <details>
3105
+ <summary><b>Only comment things that have business logic complexity</b></summary>
3106
+
3107
+ Comments are an apology, not a requirement. Good code _mostly_ documents itself.
3108
+
3109
+ **Bad:**
3110
+
3111
+ ```csharp
3112
+ public int HashIt(string data)
3113
+ {
3114
+ // The hash
3115
+ var hash = 0;
3116
+
3117
+ // Length of string
3118
+ var length = data.length;
3119
+
3120
+ // Loop through every character in data
3121
+ for (var i = 0; i < length; i++)
3122
+ {
3123
+ // Get character code.
3124
+ const char = data.charCodeAt(i);
3125
+ // Make the hash
3126
+ hash = ((hash << 5) - hash) + char;
3127
+ // Convert to 32-bit integer
3128
+ hash &= hash;
3129
+ }
3130
+ }
3131
+ ```
3132
+
3133
+ **Better but still Bad:**
3134
+
3135
+ ```csharp
3136
+ public int HashIt(string data)
3137
+ {
3138
+ var hash = 0;
3139
+ var length = data.length;
3140
+ for (var i = 0; i < length; i++)
3141
+ {
3142
+ const char = data.charCodeAt(i);
3143
+ hash = ((hash << 5) - hash) + char;
3144
+
3145
+ // Convert to 32-bit integer
3146
+ hash &= hash;
3147
+ }
3148
+ }
3149
+ ```
3150
+
3151
+ If a comment explains WHAT the code is doing, it is probably a useless comment and can be implemented with a well named variable or function. The comment in the previous code could be replaced with a function named `ConvertTo32bitInt` so this comment is still useless.
3152
+ However it would be hard to express by code WHY the developer chose djb2 hash algorithm instead of sha-1 or another hash function. In that case a comment is acceptable.
3153
+
3154
+ **Good:**
3155
+
3156
+ ```csharp
3157
+ public int Hash(string data)
3158
+ {
3159
+ var hash = 0;
3160
+ var length = data.length;
3161
+
3162
+ for (var i = 0; i < length; i++)
3163
+ {
3164
+ var character = data[i];
3165
+ // use of djb2 hash algorithm as it has a good compromise
3166
+ // between speed and low collision with a very simple implementation
3167
+ hash = ((hash << 5) - hash) + character;
3168
+
3169
+ hash = ConvertTo32BitInt(hash);
3170
+ }
3171
+ return hash;
3172
+ }
3173
+
3174
+ private int ConvertTo32BitInt(int value)
3175
+ {
3176
+ return value & value;
3177
+ }
3178
+ ```
3179
+
3180
+ **[⬆ back to top](#table-of-contents)**
3181
+
3182
+ </details>
3183
+
3184
+ # Other Clean Code Resources
3185
+
3186
+ ## Other Clean Code Lists
3187
+
3188
+ - [clean-code-javascript](https://github.com/ryanmcdermott/clean-code-javascript) - Clean Code concepts adapted for JavaScript
3189
+ - [clean-code-php](https://github.com/jupeter/clean-code-php) - Clean Code concepts adapted for PHP
3190
+ - [clean-code-ruby](https://github.com/uohzxela/clean-code-ruby) - Clean Code concepts adapted for Ruby
3191
+ - [clean-code-python](https://github.com/zedr/clean-code-python) - Clean Code concepts adapted for Python
3192
+ - [clean-code-typescript](https://github.com/labs42io/clean-code-typescript) - Clean Code concepts adapted for TypeScript
3193
+ - [clean-go-article](https://github.com/Pungyeon/clean-go-article) - Clean Code concepts adapted for Golang and an example how to apply [clean code in Golang](https://github.com/Pungyeon/clean-go)
3194
+ - [clean-abap](https://github.com/SAP/styleguides) - Clean Code concepts adapted for ABAP
3195
+ - [programming-principles](https://github.com/webpro/programming-principles) - Categorized overview of Programming Principles & Patterns
3196
+ - [Elixir-Code-Smells](https://github.com/lucasvegi/Elixir-Code-Smells) - Catalog of Elixir-specific code smells
3197
+ - [awesome-clean-code](https://github.com/kkisiele/awesome-clean-code) - Design principles, featured articles, tutorials, videos, code examples, blogs and books
3198
+
3199
+ ## Style Guides
3200
+ - [Google Styleguides](https://github.com/google/styleguide) - This project holds the C++ Style Guide, Swift Style Guide, Objective-C Style Guide, Java Style Guide, Python Style Guide, R Style Guide, Shell Style Guide, HTML/CSS Style Guide, JavaScript Style Guide, AngularJS Style Guide, Common Lisp Style Guide, and Vimscript Style Guide
3201
+ - [Django Styleguide](https://github.com/HackSoftware/Django-Styleguide) - Django styleguide used in HackSoft projects
3202
+ - [nodebestpractices](https://github.com/goldbergyoni/nodebestpractices) - The Node.js best practices list
3203
+
3204
+ ## Tools
3205
+
3206
+ - [codemaid](https://github.com/codecadwallader/codemaid) - open source Visual Studio extension to cleanup and simplify our C#, C++, F#, VB, PHP, PowerShell, JSON, XAML, XML, ASP, HTML, CSS, LESS, SCSS, JavaScript and TypeScript coding
3207
+ - [Sharpen](https://github.com/sharpenrocks/Sharpen) - Visual Studio extension that intelligently introduces new C# features into your existing code base
3208
+ - [tslint-clean-code](https://github.com/Glavin001/tslint-clean-code) - TSLint rules for enforcing Clean Code
3209
+
3210
+ ## Cheatsheets
3211
+
3212
+ - [AspNetCoreDiagnosticScenarios](https://github.com/davidfowl/AspNetCoreDiagnosticScenarios) - Examples of broken patterns in ASP.NET Core applications
3213
+ - [Clean Code](cheatsheets/Clean-Code-V2.4.pdf) - The summary of [Clean Code: A Handbook of Agile Software Craftsmanship](https://www.amazon.com/dp/0132350882) book
3214
+ - [Clean Architecture](cheatsheets/Clean-Architecture-V1.0.pdf) - The summary of [Clean Architecture: A Craftsman's Guide to Software Structure and Design](https://www.amazon.com/dp/0134494164) book
3215
+ - [Modern JavaScript Cheatsheet](https://github.com/mbeaudru/modern-js-cheatsheet) - Cheatsheet for the JavaScript knowledge you will frequently encounter in modern projects
3216
+ - [OWASP Cheat Sheet Series](https://cheatsheetseries.owasp.org) - Cheatsheet was created to provide a concise collection of high value information on specific application security topics
3217
+ - [.NET Memory Performance Analysis](https://github.com/Maoni0/mem-doc/blob/master/doc/.NETMemoryPerformanceAnalysis.md) - This document aims to help folks who develop applications in .NET with how to think about memory performance analysis and finding the right approaches to perform such analysis if they need to. In this context .NET includes .NET Framework and .NET Core. In order to get the latest memory improvements in both the garbage collector and the rest of the framework I strongly encourage you to be on .NET Core if you are not already, because that’s where the active development happens
3218
+ - [naming-cheatsheet](https://github.com/kettanaito/naming-cheatsheet) - Comprehensive language-agnostic guidelines on variables naming
3219
+ - [101 Design Patterns & Tips for Developers](https://sourcemaking.com/design-patterns-and-tips)
3220
+ - [Go Concurrency Guide](https://github.com/luk4z7/go-concurrency-guide)
3221
+ - [Cognitive Load In Software Development](https://github.com/zakirullin/cognitive-load)
3222
+
3223
+ ---
3224
+
3225
+ # Contributors
3226
+
3227
+ Thank you to all the people who have already contributed to `clean-code-dotnet` project
3228
+
3229
+ <a href="https://github.com/thangchung/clean-code-dotnet/graphs/contributors"><img src="https://opencollective.com/cleancodedotnet/contributors.svg?width=890" title="contributors" alt="contributors" /></a>
3230
+
3231
+ # Backers
3232
+
3233
+ Love our work and help us continue our activities? [[Become a backer](https://opencollective.com/cleancodedotnet#backer)]
3234
+
3235
+ <a href="https://opencollective.com/cleancodedotnet#backers" target="_blank"><img src="https://opencollective.com/cleancodedotnet/backers.svg?width=890"></a>
3236
+
3237
+ # Sponsors
3238
+
3239
+ Become a sponsor and get your logo in our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/cleancodedotnet#sponsor)]
3240
+
3241
+ <a href="https://opencollective.com/cleancodedotnet/sponsor/0/website" target="_blank"><img src="https://opencollective.com/cleancodedotnet/sponsor/0/avatar.svg"></a>
3242
+ <a href="https://opencollective.com/cleancodedotnet/sponsor/1/website" target="_blank"><img src="https://opencollective.com/cleancodedotnet/sponsor/1/avatar.svg"></a>
3243
+ <a href="https://opencollective.com/cleancodedotnet/sponsor/2/website" target="_blank"><img src="https://opencollective.com/cleancodedotnet/sponsor/2/avatar.svg"></a>
3244
+ <a href="https://opencollective.com/cleancodedotnet/sponsor/3/website" target="_blank"><img src="https://opencollective.com/cleancodedotnet/sponsor/3/avatar.svg"></a>
3245
+ <a href="https://opencollective.com/cleancodedotnet/sponsor/4/website" target="_blank"><img src="https://opencollective.com/cleancodedotnet/sponsor/4/avatar.svg"></a>
3246
+
3247
+ # License
3248
+
3249
+ [![CC0](http://mirrors.creativecommons.org/presskit/buttons/88x31/svg/cc-zero.svg)](https://creativecommons.org/publicdomain/zero/1.0/)
3250
+
3251
+ To the extent possible under law, [thangchung](https://github.com/thangchung) has waived all copyright and related or neighboring rights to this work.
3252
+