-
Notifications
You must be signed in to change notification settings - Fork 0
/
feed.xml
1991 lines (1499 loc) · 245 KB
/
feed.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Scott Hannen</title>
<description>Scott Hannen is a software development consultant specializing in improving the quality of code.</description>
<link>http://scotthannen.org/</link>
<atom:link href="http://scotthannen.org/feed.xml" rel="self" type="application/rss+xml"/>
<pubDate>Sun, 26 Jul 2020 12:26:20 -0400</pubDate>
<lastBuildDate>Sun, 26 Jul 2020 12:26:20 -0400</lastBuildDate>
<generator>Jekyll v3.8.5</generator>
<item>
<title>Sometimes It's Easier to Mock Without Moq</title>
<description><p>I like <a href="https://github.com/Moq/moq4/wiki/Quickstart">Moq</a>. It’s easy to use and it’s used frequently enough
that developers are familiar with it. But sometimes there’s an even easier way to write tests, and that
involves creating classes that mock interfaces.</p>
<p>As an example (I’ll try not to convolute this) suppose we have a class that</p>
<ul>
<li>listens to messages from a queue</li>
<li>reads the contents of the message and converts it into a command</li>
<li>invokes a command handler</li>
</ul>
<p>I want to write a test to verify that given a message with specific contents,
the command sent to the command handler has the expected properties.</p>
<p>Here’s what that test might look like using Moq:
)</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">[TestMethod]</span>
<span class="k">public</span> <span class="k">async</span> <span class="n">Task</span> <span class="nf">CommandHandlerInvokedWithCorrectCommand</span><span class="p">()</span>
<span class="p">{</span>
<span class="kt">var</span> <span class="n">commandHandlerMock</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Mock</span><span class="p">&lt;</span><span class="n">ICommandHandler</span><span class="p">&lt;</span><span class="n">DoSomethingCommand</span><span class="p">&gt;&gt;();</span>
<span class="n">DoSomethingCommand</span> <span class="n">handledCommand</span> <span class="p">=</span> <span class="k">null</span><span class="p">;</span>
<span class="n">commandHandlerMock</span><span class="p">.</span><span class="nf">Setup</span><span class="p">(</span><span class="n">x</span> <span class="p">=&gt;</span>
<span class="n">x</span><span class="p">.</span><span class="nf">HandleCommandAsync</span><span class="p">(</span><span class="n">It</span><span class="p">.</span><span class="n">IsAny</span><span class="p">&lt;</span><span class="n">DoSomethingCommand</span><span class="p">&gt;()))</span>
<span class="p">.</span><span class="n">Callback</span><span class="p">&lt;</span><span class="n">DoSomethingCommand</span><span class="p">&gt;(</span><span class="n">command</span> <span class="p">=&gt;</span> <span class="n">handledCommand</span> <span class="p">=</span> <span class="n">command</span><span class="p">);</span>
<span class="kt">var</span> <span class="n">subject</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">MessageListener</span><span class="p">(</span><span class="n">commandHandlerMock</span><span class="p">.</span><span class="n">Object</span><span class="p">);</span>
<span class="kt">var</span> <span class="n">message</span> <span class="p">=</span> <span class="nf">CreateMessage</span><span class="p">(</span><span class="s">"X"</span><span class="p">,</span> <span class="m">2</span><span class="p">);</span>
<span class="k">await</span> <span class="n">subject</span><span class="p">.</span><span class="nf">ReceiveMessage</span><span class="p">(</span><span class="n">message</span><span class="p">);</span>
<span class="n">Assert</span><span class="p">.</span><span class="nf">IsTrue</span><span class="p">(</span><span class="n">handledCommand</span><span class="p">.</span><span class="n">SomeProperty</span> <span class="p">==</span> <span class="s">"x"</span>
<span class="p">&amp;&amp;</span> <span class="n">handledCommand</span><span class="p">.</span><span class="n">SomeOtherProperty</span> <span class="p">==</span> <span class="m">2</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>
<p>In case you haven’t used this, here’s what we’re doing:</p>
<ul>
<li>Using Moq to create a <code class="highlighter-rouge">Mock&lt;ICommandHandler&lt;DoSomethingCommand&gt;&gt;</code></li>
<li>Setting up the mock so that when <code class="highlighter-rouge">HandleCommandAsync</code> is called,
it executes a callback that assigns the <code class="highlighter-rouge">DoSomethingCommand</code> parameter
passed to the command handler to the <code class="highlighter-rouge">handledCommand</code> variable so that
we can inspect the command that was sent to the handler.</li>
</ul>
<p>This isn’t bad. I’ve written it a bunch of times, and developers who’ve
used Moq know what it means. But can we make it a little simpler?
Judge for yourself.</p>
<p>In the time it takes me to set up that mock, I can create this class:</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">MockCommandHandler</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="p">:</span> <span class="n">ICommandHandler</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span>
<span class="p">{</span>
<span class="k">public</span> <span class="n">T</span> <span class="n">HandledCommand</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">private</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
<span class="k">public</span> <span class="k">async</span> <span class="n">Task</span> <span class="nf">HandleCommandAsync</span><span class="p">(</span><span class="n">T</span> <span class="n">command</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">HandledCommand</span> <span class="p">=</span> <span class="n">command</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>That took seconds. What does it do for the unit test?
I think it’s an improvement.</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">[TestMethod]</span>
<span class="k">public</span> <span class="k">async</span> <span class="n">Task</span> <span class="nf">CommandHandlerInvokedWithCorrectCommand</span><span class="p">()</span>
<span class="p">{</span>
<span class="kt">var</span> <span class="n">commandHandler</span> <span class="p">=</span> <span class="k">new</span> <span class="n">MockCommandHandler</span><span class="p">&lt;</span><span class="n">DoSomethingCommand</span><span class="p">&gt;();</span>
<span class="kt">var</span> <span class="n">subject</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">MessageListener</span><span class="p">(</span><span class="n">commandHandler</span><span class="p">);</span>
<span class="kt">var</span> <span class="n">message</span> <span class="p">=</span> <span class="nf">CreateMessage</span><span class="p">(</span><span class="s">"X"</span><span class="p">,</span> <span class="m">2</span><span class="p">);</span>
<span class="k">await</span> <span class="n">subject</span><span class="p">.</span><span class="nf">ReceiveMessage</span><span class="p">(</span><span class="n">message</span><span class="p">);</span>
<span class="kt">var</span> <span class="n">handledCommand</span> <span class="p">=</span> <span class="n">commandHandler</span><span class="p">.</span><span class="n">HandledCommand</span><span class="p">;</span>
<span class="n">Assert</span><span class="p">.</span><span class="nf">IsTrue</span><span class="p">(</span><span class="n">handledCommand</span><span class="p">.</span><span class="n">SomeProperty</span> <span class="p">==</span> <span class="s">"x"</span>
<span class="p">&amp;&amp;</span> <span class="n">handledCommand</span><span class="p">.</span><span class="n">SomeOtherProperty</span> <span class="p">==</span> <span class="m">2</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Isn’t that easier to read? It’s undeniably shorter. And I can reuse that
mock command handler in other tests. It also makes a difference if a
test necessarily sets up more dependencies. We want to keep our tests as
short and easy to read as possible.</p>
<h3 id="the-wall-of-moq">The Wall of Moq</h3>
<p>As a side note, sometimes if classes have too many dependencies we declare
a bunch of Moq mocks as private variables in our tests followed by lots of initialization code that
instantiates them and sets them up, and still individual tests have to do different setup for some of them.
All we see when we open the file is Moq.</p>
<p>That’s not a Moq problem - it’s a problem with the classes we’re testing. They
have too many dependencies. Anyway, I don’t like it. I call it “the Wall of Moq.”
It makes tests difficult to read. We’ll see mocks set up with behaviors they don’t
need because no one can keep track of which ones are needed for any one test.
Once that happens we can no longer understand either the tests or the code
we’re testing.</p>
<h3 id="its-really-easy-with-delegates">It’s Really Easy With Delegates</h3>
<p>What if instead of an <code class="highlighter-rouge">ICommandHandler&lt;T&gt;</code> interface we have a delegate,
and we inject that into our class? (More on that <a href="/blog/2018/03/18/depending-on-functions-instead-of-interfaces.html">here</a>).</p>
<p>If we inject this delegate into our message listener instead of an interface:</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">delegate</span> <span class="n">Task</span> <span class="n">CommandHandler</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;(</span><span class="n">T</span> <span class="n">command</span><span class="p">);</span>
</code></pre></div></div>
<p>…then we can use a local method as our mock:</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">[TestMethod]</span>
<span class="k">public</span> <span class="k">async</span> <span class="n">Task</span> <span class="nf">CommandHandlerInvokedWithCorrectCommand</span><span class="p">()</span>
<span class="p">{</span>
<span class="n">DoSomethingCommand</span> <span class="n">handledCommand</span> <span class="p">=</span> <span class="k">null</span><span class="p">;</span>
<span class="k">async</span> <span class="n">Task</span> <span class="nf">CommandHandlerMock</span><span class="p">(</span><span class="n">DoSomethingCommand</span> <span class="n">command</span><span class="p">)</span> <span class="p">=&gt;</span> <span class="n">handledCommand</span> <span class="p">=</span> <span class="n">command</span><span class="p">;</span>
<span class="kt">var</span> <span class="n">subject</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">MessageListener</span><span class="p">(</span><span class="n">CommandHandlerMock</span><span class="p">);</span>
<span class="kt">var</span> <span class="n">message</span> <span class="p">=</span> <span class="nf">CreateMessage</span><span class="p">(</span><span class="s">"X"</span><span class="p">,</span> <span class="m">2</span><span class="p">);</span>
<span class="k">await</span> <span class="n">subject</span><span class="p">.</span><span class="nf">ReceiveMessage</span><span class="p">(</span><span class="n">message</span><span class="p">);</span>
<span class="n">Assert</span><span class="p">.</span><span class="nf">IsTrue</span><span class="p">(</span><span class="n">handledCommand</span><span class="p">.</span><span class="n">SomeProperty</span> <span class="p">==</span> <span class="s">"x"</span>
<span class="p">&amp;&amp;</span> <span class="n">handledCommand</span><span class="p">.</span><span class="n">SomeOtherProperty</span> <span class="p">==</span> <span class="m">2</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Now we don’t have to declare a separate <code class="highlighter-rouge">MockCommandHandler</code>, and
we can still declare and set up the mock in a single succint line.</p>
<p>It’s not a huge difference, but these alternatives will save us some typing,
make it easier to reuse code in our tests, and keep our tests a little bit
easier to read. And if I’m just mocking a method that returns something
I’ll still use Moq.</p>
</description>
<pubDate>Fri, 10 Jul 2020 00:00:00 -0400</pubDate>
<link>http://scotthannen.org/blog/2020/07/10/easier-to-mock-without-moq.html</link>
<guid isPermaLink="true">http://scotthannen.org/blog/2020/07/10/easier-to-mock-without-moq.html</guid>
<category>blog</category>
</item>
<item>
<title>Pragmatism, Perfectionism, and Static Code Analysis</title>
<description><p>There are two extremes when it comes to the cleanliness and maintainability of code:</p>
<ol>
<li>I’m pragmatic. The most important thing is that it works. The other details don’t matter.</li>
<li>We should endlessly chase unattainable perfection.</li>
</ol>
<h2 id="pragmatism">“Pragmatism”</h2>
<p>Pragmatism is good, right? It means to value what is practical over what is theoretical. Unfortunately
that word is often used to mean, “I do what makes sense to me and don’t waste time learning to improve.”
It amounts to taking whatever we don’t want to learn or do and labeling it “theoretical” so we
can ignore it.</p>
<p>That’s harsh, but I’ll go a step further. I’m going to guess that most developers who call themselves
“pragmatic” couldn’t define the word without looking it up. Be wary of anyone who justifies
making messes for others to clean up by using a word they don’t understand.</p>
<h2 id="perfection">Perfection</h2>
<p>The other end of the spectrum recognizes that technical debt and defects don’t always result from large
decisions made badly. They’re caused by an accumulation of tiny choices that gradually make code harder
to understand, making changes difficult and defects more likely. Those developers scour over their own
code and that of others looking for variables with the wrong scope and interface segregation violations.</p>
<p>While I’d rather lean toward the second group than the first, that pursuit of perfection is still
problematic. Why?</p>
<p>Reviewing code to comment on every minute detail is time-consuming and introduces a long feedback cycle.
It’s also subjective. One developer says a class is large and confusing. But how large is too large? Confusing
to whom? Why?</p>
<p>It’s also a miserable experience for everyone involved. Even if I agree in principle with adhering to
exacting standards, I wouldn’t want to be on either side of that code review. I don’t want someone pointing
out 20 minor issues to me, and then five more that I introduce by fixing those 20.</p>
<p>The only thing worse is being the reviewer who finds and highlights those issues. I don’t know about
you, but I don’t have it in me to point out every single potential flaw I see, no matter how small.
Not even if I believe they matter.
I can’t sustain that for any period of time. Between the effort and my empathy for a fellow human developer
I’m going to relent, ignoring the small things and focusing on the big ones. And those small things
will accumulate. We may have empathy but our code doesn’t.</p>
<p>That brings us back to pragmatism. Seeking code utopia by carefully reviewing to enforce standards may sound
like a good idea in theory, but it’s not practical. It’s going to take too long, we’ll start to hate ourselves
and each other, and we’ll end up cutting corners anyway.</p>
<h2 id="a-pragmatic-solution---static-code-analysis">A Pragmatic Solution - Static Code Analysis</h2>
<p>How do we make consistent adherence to standards less theoretical and more practical, and therefore pragmatic?</p>
<p>What we need is feedback similar to what we get from the compiler when we make a type, omit a semicolon,
don’t close our braces, etc. The compiler is ultra nitpicky. Very little gets past it. Such constant
negative feedback coming from a person would be unbearable, but coming from the compiler we don’t take it
personally, because it isn’t. Feedback comes quickly, not in a wave that hits us a day later. It helps us.
We rely on it and value it.</p>
<p><em>Static code analysis</em> provides that feedback. After the code has compiled, a code analyzer applies another
set of rules to identify potential issues within our code, much like a human code reviewer might but with less pain.</p>
<ul>
<li>An analyzer can evaluate in a minute what would take a reviewer hours to read and document. That means less
expenditure of time and a rapid feedback cycle.</li>
<li>Its evaluation is not subjective. Teams can tweak the rules as they see fit, but an analyzer applies those rules consistently.</li>
<li>It reduces the unpleasant human experience of correcting and being corrected.</li>
</ul>
<p>Static code analysis doesn’t (or shouldn’t) eliminate code review. It just does a lot of the heavy lifting, pointing
out the small things so that we can focus on the architecture and behavior of code. And as it does so it finds issues
we might not recognize otherwise. They are not robot overlords. If we understand what they are telling us and disagree. we
can and should tweak the rules or mute them.</p>
<h2 id="ndepend">NDepend</h2>
<p>At this point I’ll start referring to a particular product, <a href="https://www.ndepend.com/">NDepend</a>. Full disclosure: I was given
a license to work with and evaluate, although not with any requirement that I advertise it or promote it. I’m not paid to
write this. I’m writing (a year later) because I’m convinced of the value of products like it and this one in particular.</p>
<h3 id="what-issues-does-it-identify">What Issues Does It Identify?</h3>
<p>There are <a href="https://www.ndepend.com/docs/code-metrics">many</a>. I’ll highlight a few.
They’re significant because any one of them can make code difficult to maintain
and increase the risk of defects. They’re also not easy for a person to spot when reviewing code:</p>
<h4 id="long-methods">Long Methods</h4>
<p>Limiting the lines of code per method is like setting a speed limit. Is 70mph really the perfect limit, and is 71mph too fast?
There’s no perfect one-size-fits-all number. But the idea isn’t that any number is perfect. Rather, if we set the limit at 70mph
then we won’t drive 120mph.</p>
<p>The same goes for lines of code. My arbitary limit is fifteen per method. It’s not perfect, but if I stick to it and only rarely
violate it, it’s impossible to write a method with 100 lines. NDepend warns that 20 is difficult to understand and maintain
while 40 or more makes a method extremely complex. You can change those numbers. The tool doesn’t carve the rules in stone -
it helps to enforce what you and your team decide so you don’t have to count lines of code.</p>
<h4 id="classes-lacking-cohesion">Classes Lacking Cohesion</h4>
<p>Massive “god classes” create all sorts of pain and are difficult to break up. What if we could spot the first step toward
creating such a class and prevent it before it even begins to grow?</p>
<p>NDepend and other methods look for cohesion in classes. Suppose a class has a method that depends on certain private fields,
and then we add another method that depends on different fields. Should that be one class? Why not put the one method with its
fields in one class and the other method with its fields in a different one? The more we add, the harder it becomes to see,
and then it snowballs. Static analysis can catch that when it starts.</p>
<h4 id="cyclomatic-complexity">Cyclomatic Complexity</h4>
<p>While not a perfect measurement, it helps to identify classes and methods in which too many decisions are made. If a method
contains so many decisions that there are 20, 30, or more paths within its execution then it may be impossible for a developer
to read it and comprehend what it’s going to do in all of those scenarios or to write tests for them.
Consider what that potentially means: We could write or modify code that we literally don’t understand.</p>
<p>I’ve heard the objection that calculations of cyclomatic complexity vary. It’s true. Compare it to thermometer that might
be off by a degree. And while we’re at it, 98.6°F isn’t everyone’s perfect temperature. But if the thermometer says your
temperature is 107°F (and you’re still conscious) you don’t worry about that one degree of accuracy.</p>
<p>That’s how I view all code metrics. They’re not magic numbers that tell us whether or not our code is perfect. They’re
guidelines that tell us when we’re at or over the limit of what’s okay.</p>
<p>Wouldn’t we want a code reviewer to say why the issues they point out matter? NDepend (and other analyzers) explain the signifance
of the rules. NDepend links to articles for further reading so that we can understand and evaluate for ourselves the principles that
underly its suggestions.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Static code analysis helps us to strike the balance between fake pragmatism and unattainable perfection. It doesn’t ensure
that we follow all of our standards and adhere to all of our principles, but it guides us in that direction. It’s harder to
violate the Single Responsibility principle if we’re not creating giant, incohesive classes with a dozen public methods. It’s
harder to violate the Interface Segregation Principle if we limit the number of methods per interface. And then the chaos and
messiness that we prevent will make it easier for human reviewers to see what remains to improve.</p>
<p>Does this sound like a sales pitch? I suppose it is. I want to work in code developed by people who use NDepend or something
like it because it’s going to be easier to understand and modify. I hate the feeling when I’ve introduce a defect and I
realize that in part it’s because the code was difficult to read, change, and test, but it was my change and I own it. It’s
going to happen. I want less of it.</p>
<p>What does it cost? Depending on the number of developers, $300-$400, more for a build server. That’s the cost of a few hours
of our time. That’s the cost of a single in-depth code review and a fraction of the cost of fixing a single defect (not counting)
the cost of the defect itself). It’s the cost of an extra few hours spent trying to understand code before we
change it.</p>
<p>Reason on it this way: It’s paid software to do what a person does except faster and more reliably, which in turn saves
money and pays for itself. That’s not a sales pitch for NDepend - it’s a sales pitch for software. It’s the underlying reason
why computers and software exist. It’s beneficial for the same reason why whatever software we’re paid to write is beneficial.</p>
<p>It’s genuine pragmatism, and I believe that it’s an edge for developers and teams who use it.</p>
</description>
<pubDate>Mon, 06 Jul 2020 00:00:00 -0400</pubDate>
<link>http://scotthannen.org/blog/2020/07/06/static-code-analysis.html</link>
<guid isPermaLink="true">http://scotthannen.org/blog/2020/07/06/static-code-analysis.html</guid>
<category>blog</category>
</item>
<item>
<title>No, MediatR Didn't Run Over My Dog</title>
<description><p>I’m slightly concerned that this could be taken as some animus-driven screed against MediatR.
But we’re using it wrong, and we’re using it wrong for the wrong reasons.
Here’s the really short TL;DR version:</p>
<h2 id="tldr">TL;DR</h2>
<p>Injecting command handler abstractions into classes that depend on command handlers is good.
Replacing that by injecting an <code class="highlighter-rouge">IMediator</code> and sending commands to that is probably bad.
The reasons given for using it are often meaningless.
We often use it to implement the service locator anti-pattern, not the mediator design pattern.</p>
<h2 id="illustrated">Illustrated</h2>
<p>This code depends on two abstractions, a command handler and a query handler. They are injected into the constructor.</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">DoesThings</span>
<span class="p">{</span>
<span class="k">private</span> <span class="k">readonly</span> <span class="n">ICommandHandler</span><span class="p">&lt;</span><span class="n">DoThisCommand</span><span class="p">&gt;</span> <span class="n">doThisHandler</span><span class="p">;</span>
<span class="k">private</span> <span class="k">readonly</span> <span class="n">IQueryHandler</span><span class="p">&lt;</span><span class="n">SomeQuery</span><span class="p">,</span> <span class="n">Data</span><span class="p">&gt;</span> <span class="n">someQueryHandler</span>
<span class="k">public</span> <span class="nf">DoesThings</span><span class="p">(</span>
<span class="n">ICommandHandler</span><span class="p">&lt;</span><span class="n">DoThis</span><span class="p">&gt;</span> <span class="n">doThisHandler</span><span class="p">,</span>
<span class="n">ICommandHandler</span><span class="p">&lt;</span><span class="n">DoThat</span><span class="p">&gt;</span> <span class="n">doThatHandler</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="n">doThisHandler</span> <span class="p">=</span> <span class="n">doThisHandler</span><span class="p">;</span>
<span class="k">this</span><span class="p">.</span><span class="n">someQueryHandler</span> <span class="p">=</span> <span class="n">IQueryHandler</span><span class="p">&lt;</span><span class="n">SomeQuery</span><span class="p">,</span> <span class="n">Data</span><span class="p">&gt;</span> <span class="n">someQueryHandler</span><span class="p">)</span>
<span class="p">}</span>
<span class="k">public</span> <span class="k">async</span> <span class="n">Task</span> <span class="nf">DoSomething</span><span class="p">(</span><span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">/// ...create a DoThisCommand</span>
<span class="k">await</span> <span class="n">doThisHandler</span><span class="p">.</span><span class="nf">Handle</span><span class="p">(</span><span class="n">doThisCommand</span><span class="p">)</span>
<span class="p">}</span>
<span class="k">public</span> <span class="n">Data</span> <span class="nf">GetData</span><span class="p">(</span><span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">/// ...create a SomeQuery</span>
<span class="kt">var</span> <span class="n">result</span> <span class="p">=</span> <span class="k">await</span> <span class="n">someQueryHandler</span><span class="p">.</span><span class="nf">Handle</span><span class="p">(</span><span class="n">query</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Replacing it with this code is detrimental, not beneficial:</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">DoesThings</span>
<span class="p">{</span>
<span class="k">private</span> <span class="k">readonly</span> <span class="n">IMediator</span><span class="p">;</span>
<span class="k">public</span> <span class="nf">DoesThings</span><span class="p">(</span><span class="n">IMediator</span> <span class="n">mediator</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="n">mediator</span> <span class="p">=</span> <span class="n">mediator</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">DoSomething</span><span class="p">(</span><span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">/// ...create a DoThisCommand</span>
<span class="n">mediator</span><span class="p">.</span><span class="nf">Send</span><span class="p">(</span><span class="n">doThisCommand</span><span class="p">)</span>
<span class="p">}</span>
<span class="k">public</span> <span class="n">Data</span> <span class="nf">GetData</span><span class="p">(</span><span class="n">Input</span> <span class="n">input</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">/// ...create a SomeQuery</span>
<span class="kt">var</span> <span class="n">result</span> <span class="p">=</span> <span class="k">await</span> <span class="n">mediator</span><span class="p">.</span><span class="nf">Handle</span><span class="p">(</span><span class="n">query</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>For the rest of this post I’ll refer to “MediatR”, but to be clear I’m not referring to any and all use of MediatR. I’m referring specifically to replacing abstracted query and command handlers (the first example) with sending commands and queries through <code class="highlighter-rouge">IMediator</code> (the second example).</p>
<h2 id="does-this-implement-the-mediator-pattern">Does This Implement the Mediator Pattern?</h2>
<p>Articles describing the mediator pattern describe it as:</p>
<ul>
<li>Simplifying complex interactions between objects</li>
<li>Reducing coupling by preventing objects from interacting directly with each other</li>
</ul>
<p>When do we use this pattern? When interactions between objects have become too complex. For example:</p>
<ul>
<li>Performing some logical behavior requires setting a number of properties on another object</li>
<li>Groups of objects must interact with each other. A common illustration is taxi drivers communicating with each
other. Instead of each taxi driver knowing about every other taxi driver and sending messages to all of them, they
send messages to a dispatcher. Now each taxi driver has a simple relationship with the dispatcher instead of a
complex relationship with lots of taxi drivers.</li>
</ul>
<p>How does replacing command and query handlers with MediatR fit this pattern? It doesn’t.</p>
<p>Injecting <code class="highlighter-rouge">IQueryHandler&lt;FooQuery&gt;</code> into a class and calling its <code class="highlighter-rouge">Handle</code> method is as simple as it gets. It is
absurd to replace</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">result</span> <span class="p">=</span> <span class="k">await</span> <span class="n">someQueryHandler</span><span class="p">.</span><span class="nf">Handle</span><span class="p">(</span><span class="n">query</span><span class="p">);</span>
</code></pre></div></div>
<p>with</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">result</span> <span class="p">=</span> <span class="k">await</span> <span class="n">mediator</span><span class="p">.</span><span class="nf">Handle</span><span class="p">(</span><span class="n">query</span><span class="p">);</span>
</code></pre></div></div>
<p>…and try to convince ourself or others that we have replaced a complex interaction with a simpler one.</p>
<p>Does it reduce coupling? Not at all. Our class already depended on an abstraction. It was not coupled to any
implementation of the command or query handler. We can add decorators to the implementations if we need to.
We can mock them in unit tests. Once we’ve accomplished that decoupling, adding another level of abstraction doesn’t make our code super-extra
200% decoupled. It’s just pointlessly “clever.”</p>
<p>If injecting an abstraction and calling a single method - simple dependency injection - creates complex interactions
and coupling and MediatR solves it, then shouldn’t every dependency injected into every class be replaced with MediatR?
Unless we’ve got something far more complex going on, it’s a solution we don’t need to a problem we don’t have.</p>
<p>Another way to tell whether we’re actually implementing the mediator pattern correctly: The mediator will be
an abstraction we define, and its name will indicate what it mediates, like <code class="highlighter-rouge">IChatRoomMessageMediator</code>. If we
have two different classes doing different things and they both depend on the same <code class="highlighter-rouge">IMediator</code> because that’s
what mediates all the things everywhere, we should revisit that.</p>
<h2 id="does-mediatr-help-us-implement-cqrs">Does MediatR Help Us Implement CQRS?</h2>
<p>Command/Query Responsibility Segregation (CQRS) means (in brief) that we avoid combining commands that change something with queries that return data. An operation is either a command or a query, but not both.</p>
<p>Look again at the two examples. Which implements CQRS? Both. Neither. Let me explain:</p>
<p>In both examples we have a command and a query, and they are separate. Was it a challenge to implement CQRS without MediatR?
Not at all. MediatR did not sprinkle magic CQRS dust on our code.
Both code samples do the same thing, the second one with a pointless extra layer of abstraction.</p>
<p>The answer is also that neither necessarily implements CQRS.
What if our query handler, which is supposed to read and not write, violates that segregation by doing something
command-like anyway? Which example prevents it? Neither.
The only way to keep our commands and queries segregated is to segregate them.
Nothing will enforce that for us.</p>
<p>I could be way off, but I suspect that some developers learn about CQRS and MediatR at the same time
and see them as more closely related than they are.
Or perhaps they get the impression that CQRS is inherently intertwined with the mediator pattern.
It’s true that MediatR provides a handler interface, encouraging us to think in terms of handlers.
But how long does it take to create those generic interfaces?
Thirty seconds? About the same time it takes to add a NuGet package?</p>
<p>And, peculiarly, MediatR names all of its interfaces <code class="highlighter-rouge">IRequestHandler</code>.
Why not <code class="highlighter-rouge">ICommandHandler</code> and <code class="highlighter-rouge">IQueryHandler</code>?
Names matter. They don’t enforce anything, but they communicate intent.
Having commands and queries both implement <code class="highlighter-rouge">IRequest</code> and their handlers implement <code class="highlighter-rouge">IRequestHandler</code> does not express the intent to keep commands separate from queries.</p>
<h2 id="what-about-reducing-the-number-of-injected-dependencies">What About Reducing the Number of Injected Dependencies?</h2>
<p>The first example above injects two dependencies, a command handler and a query handler.
In the second example, MediatR reduces that to one dependency, <code class="highlighter-rouge">IMediator</code>.
Is fewer better? It depends. In this case, no.</p>
<p>One of the many benefits of dependency injection is that we can easily look at a class and tell how many dependencies
it has and what they are.
If a class has five or more dependencies (that’s an arbitrary number) then it’s almost certainty violating the Single Responsibility Principle.
If it has ten dependencies it’s certainly violating the SRP.</p>
<p>If performing a single logical operation involves invoking multiple dependencies, creating a single abstraction
to represent that behavior (like a facade) is beneficial. How can we tell if it is? Because instead of invoking
three methods on three dependencies, we’re invoking one method on one dependency. That’s a good way to
reduce the number of dependencies.</p>
<p>But if we have three or five or ten calls to different dependencies, we merge all of those dependencies into one,
and then make the same number of calls to one dependency (MediatR), we’re sweeping the problem under the rug.</p>
<p>It’s like adding more and more unrelated methods to a single interface where they don’t belong because we don’t
want to inject more dependencies. It’s like packing <code class="highlighter-rouge">HandlePlaceSalesOrderCommand</code>,
<code class="highlighter-rouge">HandleProductInventoryQuery</code>, and <code class="highlighter-rouge">HandleDeleteAccountCommand</code> all into one interface
and leaving the door open to add keep adding more methods. If our code allows us to do all of those unrelated things
from one class without adding more dependencies, that’s a smell.</p>
<p>Injecting too many dependencies is undesirable, but it’s a problem that reveals itself as we add the <em>n</em>th dependency.
The ability to hide or obscure them is harmful because it makes the problem harder to see.</p>
<p>Is there perhaps a misunderstanding that this is where MediatR helps us with complex interactions? It doesn’t.
If we have five interactions (complex or not) with five dependencies and we replace it with the same five interactions
with one dependency, we have not reduced the complexity of interactions.</p>
<p>Finally, if we’ve got a simple class with a handful of dependencies, why are we even talking about reducing them.
A class having more than one dependency is not a problem. Unless our class has too many dependencies, reducing
the number solves a non-existent problem.</p>
<h2 id="its-a-service-locator">It’s a Service Locator</h2>
<p>The service locator is a <a href="https://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/">known anti-pattern</a>.
An example of that anti-pattern might be injecting an IoC container (like <code class="highlighter-rouge">IServiceProvider</code>) into a
class so that class can resolve dependencies from it.
A service locator version of the first two examples might look like this:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>public class DoesThings
{
private readonly IServiceProvider serviceProvider;
public DoesThings(IServiceProvider serviceProvider
{
this.serviceProvider = serviceProvider;
}
public void DoSomething(Input input)
{
/// ...create a DoThisCommand
var commandHandler = serviceProvider.GetService&lt;ICommandHandler&lt;DoThisCommand&gt;&gt;();
await commandHandler.Handle(doThisCommand)
}
public Data GetData(Input input)
{
/// ...create a SomeQuery
var queryHandler = serviceProvider.GetService&lt;IQueryHandler&lt;SomeQuery, Data&gt;&gt;();
var result = await queryHandler.Handle(query);
}
}
</code></pre></div></div>
<p>Just as the last section decribed, the service locator is an unhealthy way to combine multiple unrelated dependencies.</p>
<p>Do you see what the MediatR example has in common with the service locator example?
With the service locator example, the only way to know what the class depends on is to look for every
single reference to <code class="highlighter-rouge">serviceProvider</code> <em>and</em> to see what’s resolved from it.
It’s also easy to add behaviors to a class that don’t belong in it just by requesting difference services
that are registered with <code class="highlighter-rouge">serviceProvider</code>. What can we request? Anything that’s registered.</p>
<p>Code that depends on MediatR is similar. We must look at every use of <code class="highlighter-rouge">mediator</code> <em>and</em> see what commands or queries are sent to it.
There could be dozens of command and query handlers registered with MediatR.
What restricts a class from sending a different command or query, something unrelated to the purpose of that class?
Nothing. Those new dependencies are hidden, obscured behind the <code class="highlighter-rouge">IMediator</code>.
MediatR opens the door to the same code smells as a service locator if we use it as a service locator.</p>
<h2 id="other-thoughts-and-concerns">Other Thoughts and Concerns</h2>
<p>MediatR scans our assemblies to find classes that implement its handler interface.
Do we really have so many commands and handlers that registering them with our IoC container is a problem?
Likely not. If we do, there are NuGet packages like <a href="https://www.nuget.org/packages/Scrutor/">Scrutor</a>
that do the same thing without asserting control over how we inject those dependencies. Or we can write our own.</p>
<p>We should define the abstractions on which our classes depend, not import them from a NuGet package.
Try writing interfaces (or delegates) to represent your command and query handlers.
How long does it take to create an abstraction like <code class="highlighter-rouge">interface ICommandHandler&lt;TCommand&gt;</code> or <code class="highlighter-rouge">interface IOrderStatusQueryHandler</code>?
It’s easy.</p>
<h2 id="the-underlying-principle">The Underlying Principle</h2>
<p>Wow, that sounded dogmatic and harsh. I hope I don’t sound like MediatR murdered
someone I care about in a deal gone wrong and now I’m lurking in dark alleys waiting for the chance to get even.</p>
<p>There is an underlying principle to what may sound like dogmatism, and it has nothing specifically to do with MediatR:</p>
<p><strong>All code must justify itself. When we write code we should be able to describe in words what problems it solves.
This is also true of implementing design patterns or importing libraries.</strong></p>
<p>We don’t need to say what our reasoning is or write it. But can we think it?
Can we explain it if asked?</p>
<p>Those descriptions might sound like</p>
<blockquote>
<p>I shouldn’t modify this class and everything that depends on it so that implements a different interface.
I’ll apply the adapter pattern so that I can implement this interface without breaking changes to other code.</p>
</blockquote>
<blockquote>
<p>I need to serialize and deserialize JSON, and this well-tested library already does that.</p>
</blockquote>
<blockquote>
<p>This code works if I write it all in one line, but it might take someone longer to figure out what it does, so
if I break it up into intermediate steps the next person will be able to understand it quickly.</p>
</blockquote>
<p>If our reason is a principle that we understand then citing the principle may be sufficient explanation.</p>
<blockquote>
<p>I understand how violating the Single Responsibility Principle creates problems later that might not seem
obvious today, so I’m going to keep these unrelated functions in separate classes.</p>
</blockquote>
<p>These are not good reasons to add code or apply a pattern:</p>
<blockquote>
<p>It’s the “XYZ” pattern</p>
</blockquote>
<p>(without explaining why “XYZ” pattern is applicable or helpful in this case.)</p>
<blockquote>
<p>Here’s an article about it</p>
</blockquote>
<p>(without explaining in our own words why it’s beneficial.)</p>
<blockquote>
<p>We did it here for a reason that made sense, so now we have to do it everywhere whether we need it or not
or future developers will be confused.</p>
</blockquote>
<p>(Give future developers a little credit. They’ll be confused because we <em>did</em> something that made no sense,
not because we <em>didn’t</em>.)</p>
<p>If we use MediatR it should pass that test. We should be able to explain in our own words what complex interactions it simplified.
Does it reduce coupling? Was adding MediatR really the only way to prevent that coupling?</p>
<p>If we can answer some of those questions we should use it. It we can’t I’m on the side of leaving it out.</p>
</description>
<pubDate>Sat, 20 Jun 2020 00:00:00 -0400</pubDate>
<link>http://scotthannen.org/blog/2020/06/20/mediatr-didnt-run-over-dog.html</link>
<guid isPermaLink="true">http://scotthannen.org/blog/2020/06/20/mediatr-didnt-run-over-dog.html</guid>
<category>blog</category>
</item>
<item>
<title>Improve Your Stack Overflow Questions With Unit Tests</title>
<description><p>Suppose you’re trying to write code to solve this problem:</p>
<blockquote>
<p>I’ve got a start date and end date. I want to count the number of times between
those dates where a given day (like 10) appears.</p>
</blockquote>
<p>You try writing it, get stuck, and decide to try asking for help on <a href="https://stackoverflow.com/">Stack Overflow</a>.
You post the problem above and include the code from your Winforms app, which looks something like this:</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">Form1</span> <span class="p">:</span> <span class="n">Form</span>
<span class="p">{</span>
<span class="k">public</span> <span class="nf">Form1</span><span class="p">()</span>
<span class="p">{</span>
<span class="nf">InitializeComponent</span><span class="p">();</span>
<span class="p">}</span>
<span class="k">private</span> <span class="k">void</span> <span class="nf">btnCalculate_Click</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">try</span>
<span class="p">{</span>
<span class="kt">var</span> <span class="n">startDate</span> <span class="p">=</span> <span class="n">DateTime</span><span class="p">.</span><span class="nf">Parse</span><span class="p">(</span><span class="n">txtStartDate</span><span class="p">.</span><span class="n">Text</span><span class="p">);</span>
<span class="kt">var</span> <span class="n">endDate</span> <span class="p">=</span> <span class="n">DateTime</span><span class="p">.</span><span class="nf">Parse</span><span class="p">(</span><span class="n">txtEndDate</span><span class="p">.</span><span class="n">Text</span><span class="p">);</span>
<span class="kt">var</span> <span class="n">day</span> <span class="p">=</span> <span class="kt">int</span><span class="p">.</span><span class="nf">Parse</span><span class="p">(</span><span class="n">txtDay</span><span class="p">.</span><span class="n">Text</span><span class="p">);</span>
<span class="kt">var</span> <span class="n">numberOfTimesDayHappensInDateRange</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span>
<span class="c1">// Some code that tries to calculate this, but isn't getting</span>
<span class="c1">// the results you want</span>
<span class="n">MessageBox</span><span class="p">.</span><span class="nf">Show</span><span class="p">(</span><span class="s">$"The answer is </span><span class="p">{</span><span class="n">numberOfTimesDayHappensInDateRange</span><span class="p">}</span><span class="s">!"</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">catch</span>
<span class="p">{</span>
<span class="n">MessageBox</span><span class="p">.</span><span class="nf">Show</span><span class="p">(</span><span class="s">"I think something is wrong with the values you entered!"</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Some variation of the following will likely happen:</p>
<ul>
<li>You’ll get downvoted</li>
<li>Your question will get closed</li>
<li>You’ll get no response</li>
<li>You’ll get answers that don’t relate to your question</li>
<li>Someone will leave a comment saying, “I have no idea what you’re trying to do. Can you give an example showing what results you expect?”</li>
</ul>
<p>We’re sad when that happens. How can we improve our question?
One approach is to write a unit test that shows our inputs and the results
we expect.</p>
<p><em>Disclaimer: I asked some other folks on Stack Overflow what they thought of this.
The response amounted to, “Sure, but no one is going to do that.” And they might be right.
But that’s okay. I’m an optimist and I like to think this will help someone, even
if it has nothing to do with asking questions on Stack Overflow.</em></p>
<p>What if we could make this easier to understand by isolating the code that contains the problem from everything else?</p>
<p>We could start by putting just this part of the code in a separate class and method:</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">static</span> <span class="k">class</span> <span class="nc">DateFunctions</span>
<span class="p">{</span>
<span class="k">public</span> <span class="k">static</span> <span class="kt">int</span> <span class="nf">NumberOfTimesDayOfMonthOccursInDateRange</span><span class="p">(</span>
<span class="n">DateTime</span> <span class="n">startDate</span><span class="p">,</span> <span class="n">DateTime</span> <span class="n">endDate</span><span class="p">,</span> <span class="kt">int</span> <span class="n">dayOfMonth</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">// Some code that tries to calculate this, but isn't getting</span>
<span class="c1">// the results you want</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p><em>In case it’s not obvious yet, this post doesn’t include a working version of this function. This is about how to ask the question,
not the solution itself.</em></p>
<p>That’s a long function name, isn’t it? But it’s also a lot clearer what it’s supposed to return. If we just called it <code class="highlighter-rouge">NumberOfTimesDayOccursInDateRange</code>
it might be less obvious that we’re talking about a calendar day (1, 15, 27) and not a day of the week (Monday, Tuesday.)</p>
<p>All we’ve done so far is move the code from one place to another. That’s a start. Now someone who wants to understand the method
and help us with it doesn’t have to look at all of the extra code. What they’re looking at is just the part we’re trying to figure out.</p>
<p>It might seem obvious to us what results we expect to get for different inputs, but how can we communicate that clearly to someone else?</p>
<p>One way to accomplish that is with one or more unit tests. If we don’t already have a unit test project in our solution, we can add one:</p>
<p>Right-click on the <em>solution</em> and select Add -&gt; New Project… -&gt; Visual C# -&gt; Test -&gt; Unit Test Project (.NET Framework).</p>
<p>There are other options such as NUnit and xUnit, but we’ll just look at Microsoft’s default version. The others do essentially the
same thing but with additional capabilities.</p>
<p>Our project will contain a single test class with a single unit test, like this:</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">namespace</span> <span class="nn">UnitTestProject1</span>
<span class="p">{</span>
<span class="p">[</span><span class="n">TestClass</span><span class="p">]</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">UnitTest1</span>
<span class="p">{</span>
<span class="p">[</span><span class="n">TestMethod</span><span class="p">]</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">TestMethod1</span><span class="p">()</span>
<span class="p">{</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>The <code class="highlighter-rouge">[TestClass]</code> attribute indicates that the class contains tests. The <code class="highlighter-rouge">[TestMethod]</code> attribute indicates that the method
<em>is</em> a test. This is how the test runner knows which parts of the code in this project are tests that we need to run.</p>
<p>For the sake of simplicity, a unit test is a method that <em>passes</em> if it runs without throwing any exceptions, and <em>fails</em> if
it throws an exception. We write these methods so that if our code does what we expect it to do, it won’t throw an exception.
It will pass. If doesn’t do what we expect, it will throw an exception and fail.</p>
<p>This will be clearer with an example. First, let’s copy our <code class="highlighter-rouge">DateFunctions</code> class into the same file as our test. We don’t have
to do that. Eventually that class will be in our “real” project - not the test project - and our test project will reference it.
But at this step it’s often convenient to have them both in one place. It’s going to help with our Stack Overflow question. This
is also how I work if I’m answering someone’s question and I want to be sure that my answer works. I just create a test project
and write both the code and the unit tests.</p>
<p>Here’s what our file looks like with the <code class="highlighter-rouge">DateFunctions</code> class included and a simple unit test:</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">[TestClass]</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">DateFunctionTests</span>
<span class="p">{</span>
<span class="p">[</span><span class="n">TestMethod</span><span class="p">]</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">NumberOfTimesDayOfMonthOccursInDateRange_returns_correct_result</span><span class="p">()</span>
<span class="p">{</span>
<span class="kt">var</span> <span class="n">startDate</span> <span class="p">=</span> <span class="n">DateTime</span><span class="p">.</span><span class="nf">Parse</span><span class="p">(</span><span class="s">"1/1/2019"</span><span class="p">);</span>
<span class="kt">var</span> <span class="n">endDate</span> <span class="p">=</span> <span class="n">DateTime</span><span class="p">.</span><span class="nf">Parse</span><span class="p">(</span><span class="s">"2/15/2019"</span><span class="p">);</span>
<span class="kt">var</span> <span class="n">dayOfMonth</span> <span class="p">=</span> <span class="m">14</span><span class="p">;</span>
<span class="kt">var</span> <span class="n">expectedResult</span> <span class="p">=</span> <span class="m">2</span><span class="p">;</span>
<span class="kt">var</span> <span class="n">actualResult</span> <span class="p">=</span> <span class="n">DateFunctions</span><span class="p">.</span><span class="nf">NumberOfTimesDayOfMonthOccursInDateRange</span><span class="p">(</span><span class="n">startDate</span><span class="p">,</span> <span class="n">endDate</span><span class="p">,</span> <span class="n">dayOfMonth</span><span class="p">);</span>
<span class="n">Assert</span><span class="p">.</span><span class="nf">AreEqual</span><span class="p">(</span><span class="n">expectedResult</span><span class="p">,</span> <span class="n">actualResult</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">public</span> <span class="k">static</span> <span class="k">class</span> <span class="nc">DateFunctions</span>
<span class="p">{</span>
<span class="k">public</span> <span class="k">static</span> <span class="kt">int</span> <span class="nf">NumberOfTimesDayOfMonthOccursInDateRange</span><span class="p">(</span>
<span class="n">DateTime</span> <span class="n">startDate</span><span class="p">,</span> <span class="n">DateTime</span> <span class="n">endDate</span><span class="p">,</span> <span class="kt">int</span> <span class="n">dayOfMonth</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">return</span> <span class="m">0</span><span class="p">;</span>
<span class="cm">/*
* I just put this here so it compiles. This would be your
* work in progress code. You've written something. It just
* doesn't return the right results.
*/</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>I made the test a little bit verbose, declaring everything as a variable, to make it easier to follow.
It shows that we’re going to execute our function with specific inputs, and we know what result
we expect.</p>
<p>The last statement - <code class="highlighter-rouge">Assert.AreEqual</code> - will check to see if our actual result is the same as our
expected result. If it is not, it will throw an exception and the test will fail.</p>
<p>To try it out, right-click on the test class and select <strong>Run Test(s)</strong>. The project will compile, Visual Studio
will run the test, and a “Test Explorer” window will open showing us the result.</p>
<p>This test will fail, because our function returned <em>0</em>, not the expected result. If we drill down into that
test result by clicking on the red “X” icons, we’ll eventually see this exception:</p>
<blockquote>
<p>Message: Assert.AreEqual failed. Expected:&lt;2&gt;. Actual:&lt;0&gt;.</p>
</blockquote>
<p>If we figure out how to fix our method so that it returns the correct result, this
test will no longer fail. Our test results will be green, not red.</p>
<p>If we want to step through the code, we can set breakpoints and then right-click
and select <strong>Debug Test(s)</strong>. This will enable us to step through the code.</p>
<h3 id="how-this-is-better-so-far">How This Is Better, So Far</h3>
<p>Let’s say that you’re trying over and over again to fix your function.
Which is easier:</p>
<ul>
<li>Starting up your Windows Forms app, typing in some values, pressing the button, and looking at the result</li>
<li>Running a unit test and seeing if it passes or fails</li>
</ul>
<p>The unit test is much easier. Perhaps we’ve already caught on that creating a form
is a horrible way to test. Maybe we tend to use console apps instead. Even still, isn’t running a unit test even easier than that?
A unit test is a lot like a console app, except that instead of us <em>looking</em> at the result to see if it’s correct,
the test already knows what the correct result is that it’s looking for. It’s built into the test.</p>
<p>Imagine if we pasted this code into our Stack Overflow question. It says, in effect,</p>
<blockquote>
<p>Here’s the code I need help with. Here’s a unit test that describes exactly what it should do.</p>
</blockquote>
<p>If I were trying to help with this question, I would probably start by creating a unit test project,
pasting this code into it, and writing some unit tests. I would use the unit tests
to confirm that my solution works. (I want to give you a good answer, which means I’m not going to guess.)</p>
<p>But now, by providing both your code and the unit test, you’ve made it even easier
to help you. I can paste both the code and the unit test, and all I’ve got to do is
work with your code to make the unit test pass.</p>
<h3 id="it-gets-even-better">It Gets Even Better</h3>
<p>Do we really trust that our code works as expected because it returns the correct
result for just one set of inputs? Wouldn’t we rather test it with multiple inputs? Maybe
we have some weird edge cases. How do we test this with multiple inputs?</p>
<p>We could copy and paste the test method so that we have several test methods,
each with different inputs and expected outputs, and then we could run all of those tests.
That’s acceptable. That means that we can test our code with a range of inputs
all at the same time. Imagine trying that with a console app. It would be a pain.
Unit tests make it easy.</p>
<p>But there’s an easier approach than creating multiple tests. We can create a
single test that takes multiple inputs. This is called <em>parameterized test</em>.
It might look like this:</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">[TestClass]</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">DateFunctionTests</span>
<span class="p">{</span>
<span class="p">[</span><span class="n">DataTestMethod</span><span class="p">]</span>
<span class="p">[</span><span class="nf">DataRow</span><span class="p">(</span><span class="s">"1/1/2019"</span><span class="p">,</span> <span class="s">"2/15/2019"</span><span class="p">,</span> <span class="m">14</span><span class="p">,</span> <span class="m">2</span><span class="p">)]</span>
<span class="p">[</span><span class="nf">DataRow</span><span class="p">(</span><span class="s">"1/1/2019"</span><span class="p">,</span> <span class="s">"1/13/2019"</span><span class="p">,</span> <span class="m">14</span><span class="p">,</span> <span class="m">0</span><span class="p">)]</span>
<span class="p">[</span><span class="nf">DataRow</span><span class="p">(</span><span class="s">"1/1/2019"</span><span class="p">,</span> <span class="s">"12/31/2019"</span><span class="p">,</span> <span class="m">31</span><span class="p">,</span> <span class="m">7</span><span class="p">)]</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">NumberOfTimesDayOfMonthOccursInDateRange_returns_correct_result</span><span class="p">(</span>
<span class="kt">string</span> <span class="n">startDate</span><span class="p">,</span> <span class="kt">string</span> <span class="n">endDate</span><span class="p">,</span> <span class="kt">int</span> <span class="n">dayOfMonth</span><span class="p">,</span> <span class="kt">int</span> <span class="n">expectedResult</span><span class="p">)</span>
<span class="p">{</span>
<span class="kt">var</span> <span class="n">actualResult</span> <span class="p">=</span> <span class="n">DateFunctions</span><span class="p">.</span><span class="nf">NumberOfTimesDayOfMonthOccursInDateRange</span><span class="p">(</span>
<span class="n">DateTime</span><span class="p">.</span><span class="nf">Parse</span><span class="p">(</span><span class="n">startDate</span><span class="p">),</span> <span class="n">DateTime</span><span class="p">.</span><span class="nf">Parse</span><span class="p">(</span><span class="n">endDate</span><span class="p">),</span> <span class="n">dayOfMonth</span><span class="p">);</span>
<span class="n">Assert</span><span class="p">.</span><span class="nf">AreEqual</span><span class="p">(</span><span class="n">expectedResult</span><span class="p">,</span> <span class="n">actualResult</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Each <code class="highlighter-rouge">DataRow</code> attribute contains a set of values - a start date, an end date, a day of the month,
and an expected result. Instead of having to write more test methods to test a different
set of values, we can just add a new data row. The test runner will run the test once
for each set of values.</p>
<p>Imagine the frustration if we fix the function so that it works with one set of inputs,
but then returns the wrong results for different inputs. Imagine having to test over and over
with each set of inputs. Now it’s easy to verify that the function returns the
correct result for all of the inputs at the same time.</p>
<h3 id="our-improved-question">Our Improved Question</h3>
<p>Now, instead of posting a bunch of irrelevant code that other people have to read through,
we can post this:</p>
<hr />
<p>I’m trying to write a function that returns the number of times a given day of the
month appears in a date range. Here’s my code, which isn’t working yet, and
some unit tests that show what the results should be.</p>
<p>Can you help me to find the problem in my code?</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">static</span> <span class="k">class</span> <span class="nc">DateFunctions</span>
<span class="p">{</span>
<span class="k">public</span> <span class="k">static</span> <span class="kt">int</span> <span class="nf">NumberOfTimesDayOfMonthOccursInDateRange</span><span class="p">(</span>
<span class="n">DateTime</span> <span class="n">startDate</span><span class="p">,</span> <span class="n">DateTime</span> <span class="n">endDate</span><span class="p">,</span> <span class="kt">int</span> <span class="n">dayOfMonth</span><span class="p">)</span>
<span class="p">{</span>
<span class="c1">// Whatever code you have that isn't working right</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="na">[TestClass]</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">DateFunctionTests</span>
<span class="p">{</span>
<span class="p">[</span><span class="n">DataTestMethod</span><span class="p">]</span>
<span class="p">[</span><span class="nf">DataRow</span><span class="p">(</span><span class="s">"1/1/2019"</span><span class="p">,</span> <span class="s">"2/15/2019"</span><span class="p">,</span> <span class="m">14</span><span class="p">,</span> <span class="m">2</span><span class="p">)]</span>
<span class="p">[</span><span class="nf">DataRow</span><span class="p">(</span><span class="s">"1/1/2019"</span><span class="p">,</span> <span class="s">"1/13/2019"</span><span class="p">,</span> <span class="m">14</span><span class="p">,</span> <span class="m">0</span><span class="p">)]</span>
<span class="p">[</span><span class="nf">DataRow</span><span class="p">(</span><span class="s">"1/1/2019"</span><span class="p">,</span> <span class="s">"12/31/2019"</span><span class="p">,</span> <span class="m">31</span><span class="p">,</span> <span class="m">8</span><span class="p">)]</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">NumberOfTimesDayOfMonthOccursInDateRange_returns_correct_result</span><span class="p">(</span>
<span class="kt">string</span> <span class="n">startDate</span><span class="p">,</span> <span class="kt">string</span> <span class="n">endDate</span><span class="p">,</span> <span class="kt">int</span> <span class="n">dayOfMonth</span><span class="p">,</span> <span class="kt">int</span> <span class="n">expectedResult</span><span class="p">)</span>
<span class="p">{</span>
<span class="kt">var</span> <span class="n">actualResult</span> <span class="p">=</span> <span class="n">DateFunctions</span><span class="p">.</span><span class="nf">NumberOfTimesDayOfMonthOccursInDateRange</span><span class="p">(</span>
<span class="n">DateTime</span><span class="p">.</span><span class="nf">Parse</span><span class="p">(</span><span class="n">startDate</span><span class="p">),</span> <span class="n">DateTime</span><span class="p">.</span><span class="nf">Parse</span><span class="p">(</span><span class="n">endDate</span><span class="p">),</span> <span class="n">dayOfMonth</span><span class="p">);</span>
<span class="n">Assert</span><span class="p">.</span><span class="nf">AreEqual</span><span class="p">(</span><span class="n">expectedResult</span><span class="p">,</span> <span class="n">actualResult</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<hr />
<p>You may have seen people on Stack Overflow ask for an <a href="https://stackoverflow.com/help/minimal-reproducible-example">MCVE</a> which
stands for “Minimal, Complete, Verifiable Example.” In other words, they’re
asking you to provide just the part of your code that you need help with, not
all sorts of extraneous details, make sure you don’t leave out the important parts,
and show how you know whether or not it’s working.</p>
<p>That’s exactly what we’ve accomplished:</p>
<ul>
<li><strong>Minimal</strong> - we’ve stripped away all of the code that’s <em>not</em> related to the
date function.</li>
<li><strong>Complete</strong> - the whole date calculation is in that function</li>
<li><strong>Verifiable</strong> - the unit test shows both what you expect and how you know if it’s working.</li>
</ul>
<p>Assuming that you’ve made some effort to write the code - you’re showing your attempt at writing the function -
you’ve written the perfect question.</p>
<h3 id="the-best-part">The Best Part</h3>
<p>The effort that you put into asking this question will make understanding and
debugging your code so much easier that you’re far more likely to solve your own
problem before you even post the question.</p>
<p>These are roughly the same steps that most developers take to make their own problems
easier to understand and solve. We put code that performs specific functions into separate
classes and methods so that we can test it in isolation from other code. And then
we write unit tests to verify that our code does what we think it should do.</p>
<p>We all make mistakes in our code, even in code that should seem trivial. This allows
us to catch our mistakes more quickly. We can often find our mistakes right after we make them.
It also means that if we must step through our code in the debugger, we won’t have to step through
as much of it. Instead of setting breakpoints, starting up an app, and providing inputs just to test some
tiny piece of code, we can isolate just the part we’re working on.</p>
<p>In the long run this means that we work faster and with greater confidence. If we haven’t worked with unit tests
we might expect that writing the extra test code will cause us to work more slowly, but it’s actually the opposite.
When we subtract the time that we would have spent searching for defects that turn up later, re-reading code we
wrote days or weeks ago, and stepping through lots of code in the debugger, the net result is that we save lots of time.</p>
<p>It’s not immediate. There is a little bit of a learning curve, and it might slow us down at first.
But if you were ever going to a make a leap of faith, this is the one to make. Once you’re on the other side of it, you’ll
never want to go back. You might even find yourself wondering how you ever wrote code without unit tests. It’s that good.</p>
<p>You may have read articles critical of unit testing, arguing that we can end up writing way too many useless tests and that
it somehow damages the design of our code. There is usually an element of truth to such arguments. We may lose our balance
at first and veer from writing no tests to writing too many. The quality of our tests might be low. That’s okay. It’s part
of the learning experience. It helps if we realize that by not writing any unit tests, we’re already at one extreme. We may
go to the opposite extreme before finding our balance.</p>
<p>As much as this practice has helped me, I still have a great deal to learn about unit testing.</p>
<p>Unit testing is also like a gateway drug that leads to all sorts of improved practices. In this example we had to move code
out of a Windows Form into its own class so that we could test it. That’s a good habit. Making it possible to test the code
improved the design of the code. That pattern repeats. Over time we’re likely to find that arranging our code so that we
can write tests for it significantly improves the design of our code in other ways.</p>
<hr />
<p>Was the premise of this whole post just a trick to introduce unit tests? Yes and no. I often read Stack Overflow questions
that would be much easier to understand if they included unit tests to describe the expected results. Sometimes I demonstrate
the idea by including unit tests in the answer, but explaining how to write tests would be way outside the scope of the
original question.</p>
<p>At the same time, I’m convinced that most developers who don’t write unit tests would benefit from learning to write them.
As I hope I’ve demonstrated, they change the way we write our code, making it easier to isolate and solve our own problems.
We all get stuck and need help. I look things up on Stack Overflow all the time. But this change increases our ability to
push through problems on our own, increasing both our productivity and our confidence.</p>
</description>
<pubDate>Mon, 02 Sep 2019 00:00:00 -0400</pubDate>
<link>http://scotthannen.org/blog/2019/09/02/improve-stack-overflow-questions-unit-tests.html</link>
<guid isPermaLink="true">http://scotthannen.org/blog/2019/09/02/improve-stack-overflow-questions-unit-tests.html</guid>
<category>blog</category>
</item>
<item>
<title>Untestable Code Knows No Mercy</title>
<description><p>What is untestable code?</p>
<ul>
<li>It has no unit tests.</li>
<li>Writing unit tests for it would be difficult or impossible without modifying the code.</li>
<li>Common attributes include global state, tight coupling, and long methods that do lots of things.</li>
</ul>
<p>Testable code, on the other hand, tends to consist of smaller classes and methods with well-defined purposes. It avoids use of global state and uses a reasonable amount of abstraction to avoid tight coupling between components.</p>
<p>Neither is meant to be a comprehensive definition. They’re just enough so that I can throw around the terms <em>testable code</em> and <em>untestable code</em> for the rest of this post.</p>
<p>Untestable code is a cause that produces known effects. Those effects include:</p>
<ul>
<li>More defects</li>
<li>Modifications are harder and riskier</li>
<li>End users wait longer for new features and bug fixes</li>
</ul>
<p>Conversely, testable code results in the reduction of all three.</p>
<p>I hope that this is exciting, good news for at least a few people. The problems I’ve just summarized aren’t inevitable. They are effects that come from causes, and we can control those causes.</p>
<p>Why the emphasis on cause and effect? Because sometimes we understand them but somehow think that they won’t apply in certain cases. We know what results from untestable code but act as if we don’t.</p>
<p>I’ve addressed one such case <a href="http://scotthannen.org/blog/2018/04/03/tame-your-dependency-injection-registration.html">in this blog post</a>. Sometimes we use IoC containers to make our code more testable, and then we write hundreds or more lines of untestable code to configure the containers. Eventually we find it difficult to understand the code that composes the rest of our application. How does this happen? Because somehow we imagine that our dependency registration code is the exception to all the rules we normally set for ourselves, so we put it in a few massive methods and we don’t write tests for it. Then it gives us trouble because that’s what large methods without tests do.</p>
<p>SQL stored procedures are another problem area for untestable code. Have you ever observed that teams can be careful and meticulous in C# but then go crazy in SQL? It doesn’t help that the language inherently favors optimization over all other concerns. We think in terms of what we want to do with individual records but then we have to code it using set-based operations. We express behaviors in inner and outer joins and make critical decisions with inline functions that appear in unexpected places. This makes it much harder to read complex code and understand what it does and why.</p>
<p>We can’t avoid global state in SQL because tables <em>are</em> global state. It’s hard to avoid tight coupling when we’re forced to repeat lists of columns so that adding a column or changing a data type in one table can lead to cascading changes in any statement that touches it.</p>
<p>There are <a href="https://tsqlt.org/">testing frameworks</a> that address some of these concerns, and it’s possible to break large procedures into smaller ones that pass data using table variables. I’ve yet to see a team use either approach. I’m convinced that testable SQL is possible. We just don’t think about it that way.</p>