-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.xml
2883 lines (2760 loc) · 321 KB
/
index.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" standalone="yes"?>
<rss version="2.0"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
<title></title>
<link>https://www.vijayanant.com/</link>
<description>Recent content on </description>
<generator>Hugo -- gohugo.io</generator>
<language>en-us</language>
<lastBuildDate>Mon, 03 Apr 2023 00:00:00 +0000</lastBuildDate><atom:link href="https://www.vijayanant.com/index.xml" rel="self" type="application/rss+xml" />
<item>
<title>Design Principles and Design Patterns</title>
<link>https://www.vijayanant.com/posts/design-principles-and-design-patterns/</link>
<pubDate>Mon, 03 Apr 2023 00:00:00 +0000</pubDate>
<guid>https://www.vijayanant.com/posts/design-principles-and-design-patterns/</guid>
<description>Design principles and design patterns are related but serve different purposes.
Design principles are high-level guidelines for designing software that helps developers create code that is maintainable, extensible, and adaptable. These principles are not specific to any programming language or technology and can be applied to any software development project. Design principles provide a foundation for good software design and help developers create code that is easier to maintain and change over time.</description>
<content:encoded><p>Design principles and design patterns are related but serve different purposes.</p>
<p><em>Design principles</em> are high-level guidelines for designing software that helps
developers create code that is maintainable, extensible, and adaptable. These
principles are not specific to any programming language or technology and can be
applied to any software development project. Design principles provide a
foundation for good software design and help developers create code that is
easier to maintain and change over time.</p>
<p><em>Design patterns</em>, on the other hand, are specific solutions to recurring design
problems in software development. They are practical, reusable solutions that
can be applied to specific programming languages or technologies. Design
patterns are based on design principles but provide specific implementations
that can be used to solve specific problems. They also help developers avoid
common pitfalls in software development and ensure that their code is efficient,
scalable, and easy to understand.</p>
<p>The relationship between design patterns and design principles is complimentary.
Design principles provide high-level guidelines and best practices for designing
software. Design patterns provide concrete implementations to specific design
problems while adhering to the design principles</p>
<p>In fact, many design patterns provide solutions that adhere to multiple
principles. While it is ideal for a design pattern to adhere to all the design
principles, it is not always possible to achieve this. Design principles are not
absolute rules that must be followed in all cases. Some design principles may be
more important than others depending on the specific problem being solved, and
some principles may even conflict with each other. There may be situations where
adhering to a design principle is not practical or even desirable, and in such
cases, a design pattern that addresses the specific problem at hand may be a
better choice.</p>
<p>Let us see some examples:</p>
<h3 id="single-responsibility-principle-srp">Single Responsibility Principle (SRP)</h3>
<p>The SRP states that a class should have only one responsibility or reason to
change. This means that a class should only be responsible for one thing, and if
that thing changes, the class should be the only one that needs to change. The
goal is to keep classes focused and maintainable and reduce the risk of
unintended consequences when making changes.</p>
<ul>
<li>
<p>The Observer Pattern: The Observer pattern is a behavioural design pattern
that defines a one-to-many dependency between objects, where a change in one
object (the subject) causes all its dependents (observers) to be notified and
updated automatically. This pattern adheres to the SRP by separating the
responsibilities of the subject and the observers. The subject&rsquo;s
responsibility is to manage the state and notify the observers, while the
observers' responsibility is to respond to the notifications and update
themselves.</p>
</li>
<li>
<p>The Command Pattern: The Command pattern is a behavioural design pattern that
encapsulates a request as an object, thereby allowing for the separation of
the requester (client) from the executor (receiver) of the request. This
pattern adheres to the SRP by separating the responsibility of the client from
the responsibility of the receiver. The client&rsquo;s responsibility is to create
and invoke the command objects, while the receiver&rsquo;s responsibility is to
execute the commands.</p>
</li>
</ul>
<h3 id="openclosed-principle-ocp">Open/Closed Principle (OCP)</h3>
<p>The OCP states that software entities should be open for extension but closed
for modification. This means that you should be able to add new functionality to
a system without changing the existing code. The goal is to reduce the risk
of introducing new bugs when making changes and allow for greater
flexibility and adaptability in the system.</p>
<ul>
<li>
<p>The Strategy Pattern: The Strategy pattern is a behavioural design pattern
that defines a family of algorithms, encapsulates each one, and makes them
interchangeable. This pattern adheres to the OCP by allowing the behaviour of
an object to be modified without changing its class. The behaviour of an object
can be modified by changing the strategy object that the object uses.</p>
</li>
<li>
<p>The Decorator Pattern: The Decorator pattern is a structural design pattern
that allows behaviour to be added to an individual object, either statically or
dynamically, without affecting the behaviour of other objects from the same
class. This pattern adheres to the OCP by allowing functionality to be added
to an object without changing its interface or the behaviour of other objects.</p>
</li>
</ul>
<h3 id="liskov-substitution-principle-lsp">Liskov Substitution Principle (LSP)</h3>
<p>The LSP states that subtypes must be substitutable for their base types. This
means that if you have a variable of a certain type, you should be able to
substitute any subtype of that type without affecting the behaviour of the
system. The goal is to ensure that code is reusable and maintainable and reduce
the risk of introducing bugs when making changes.</p>
<ul>
<li>
<p>The Factory Method Pattern: The Factory Method pattern is a creational design
pattern that defines an interface for creating objects, but allows subclasses
to decide which class to instantiate. This pattern adheres to the LSP by
ensuring that the objects created by the factory can be used interchangeably,
regardless of their concrete types.</p>
</li>
<li>
<p>The Template Method Pattern: The Template Method pattern is a behavioural
design pattern that defines the skeleton of an algorithm in a superclass, but
lets subclasses override specific steps of the algorithm without changing its
structure. This pattern adheres to the LSP by ensuring that the subclasses can
be used in place of the superclass without changing the correctness of the
algorithm.</p>
</li>
</ul>
<h3 id="interface-segregation-principle-isp">Interface Segregation Principle (ISP)</h3>
<p>The ISP states that clients should not be forced to depend on interfaces they do
not use. This means that if a client only needs a subset of the functionality
provided by an interface, it should only depend on that subset. The goal is to
reduce coupling between components and make it easier to change or replace
components without affecting the behaviour of the system.</p>
<ul>
<li>
<p>The Adapter Pattern: The Adapter pattern is a structural design pattern that
allows incompatible classes to work together by converting the interface of
one class into another interface that the client expects. This pattern adheres
to the ISP by ensuring that the adapter only provides the methods that are
relevant to the client, and not the entire interface of the adapted class.</p>
</li>
<li>
<p>The Observer Pattern: The Observer pattern is a behavioural design pattern
that defines a one-to-many dependency between objects, such that when the
object changes state, all its dependents are notified and updated
automatically. This pattern adheres to the ISP by ensuring that the Observer
interface only includes the methods required by the observers to receive
notifications from the subject, and not any additional methods that may not be
relevant or used.</p>
</li>
</ul>
<h3 id="dependency-inversion-principle-dip">Dependency Inversion Principle (DIP)</h3>
<p>The DIP states that high-level modules should not depend on low-level modules.
Instead, both should depend on abstractions. This means that the details of how
a system works should be hidden behind abstractions, and changes to the
implementation should not affect the behaviour of the system. The goal is to make
systems more modular and easier to maintain.</p>
<ul>
<li>
<p>The Dependency Injection Pattern: The Dependency Injection pattern is a design
pattern that allows the creation of dependent objects to be inverted and
delegated to a separate component, thereby decoupling the client from the
implementation details of the dependent objects. This pattern adheres to the
DIP by ensuring that the client depends only on abstractions, and not on
concrete implementations, thus allowing for flexibility and easy substitution
of dependencies.</p>
</li>
<li>
<p>The Strategy Pattern: The Strategy pattern is a behavioural design pattern
that defines a family of algorithms, encapsulates each one, and makes them
interchangeable at runtime. This pattern adheres to the DIP by ensuring that
the algorithms are defined as interfaces or abstract classes, which can be
easily extended or modified without affecting the client code.</p>
</li>
</ul>
<h2 id="the-other-way-around">The Other Way Around</h2>
<p>It is also possible for a single design pattern to cater for more than one
design principle. Design patterns are in widespread use because they do not go
against any of the principles and address many (if not all) design principles.
For example -</p>
<ul>
<li>
<p>The Strategy pattern is often used to address the Open/Closed Principle (OCP)
and the Single Responsibility Principle (SRP) at the same time. The OCP states
that software entities should be open for extension but closed for
modification, while the SRP states that a class should have only one reason to
change. The Strategy pattern allows the behaviour of an object to be modified
at runtime without modifying the object itself, thus adhering to the OCP. It
also separates the implementation of the algorithm from the object that uses
it, adhering to the SRP.</p>
</li>
<li>
<p>The Factory Method pattern can address the SRP, the OCP, and the Dependency
Inversion Principle (DIP) at the same time. The Factory Method pattern
separates the creation of objects from their use, allowing for greater
flexibility in object creation and adherence to the SRP. It also allows for
the creation of objects at runtime, adhering to the OCP. Finally, by using
abstractions to create objects, it adheres to the DIP.</p>
</li>
</ul>
<p>While it is important to understand the concepts behind each design pattern, it
is also important to choose the right pattern for the specific problem you are
trying to solve. Not all patterns will apply to every situation, and it
is important to consider the trade-offs and benefits of each pattern before
choosing the one that is best suited for your needs.</p>
<p>In conclusion, the five major design principles and design patterns are
essential for creating maintainable, extensible, and adaptable code. By
following these principles and patterns, developers can reduce the risk of
introducing bugs when making changes, and make systems more modular and easier
to maintain, and create code that is easier to test and reuse.</p>
</content:encoded>
</item>
<item>
<title>Why YOU Should Blog Too!</title>
<link>https://www.vijayanant.com/posts/why-you-should-blog-too/</link>
<pubDate>Thu, 30 Mar 2023 13:21:32 +0530</pubDate>
<guid>https://www.vijayanant.com/posts/why-you-should-blog-too/</guid>
<description>When I first thought about blogging it was daunting. Even though I liked the idea of blogging, I didn&rsquo;t know why I should blog. What was I going to add to the world when all I know comes from reading other&rsquo;s books and blogs? I had no reason to write about topics that are already written about extensively by experts in that area. I didn&rsquo;t think I knew enough contribute.</description>
<content:encoded><p>When I first thought about blogging it was daunting. Even though I liked the
idea of blogging, I didn&rsquo;t know why I should blog. What was I going to add to
the world when all I know comes from reading other&rsquo;s books and blogs? I had no
reason to write about topics that are already written about extensively by
experts in that area. I didn&rsquo;t think I knew enough contribute.</p>
<p>Then I found a reason &ndash; to document my own learnings. It was supposed to be my
notebook. I started to document things I had learnt and things I was learning at
that moment. It was a &lsquo;blog&rsquo; in the sense that it was on the web. Few of the
&lsquo;notes&rsquo;, I felt, were better than the others. I shared them with few friends.
They liked it and encouraged me to start a &lsquo;blog&rsquo;. Even though I was not sure
they convinced me that there was nothing to lose. That&rsquo;s how I started to write.</p>
<p>Blogging isn&rsquo;t for everyone. Tons of amazing developers don&rsquo;t have blogs or
personal websites at all. I write because it&rsquo;s fun for me and it helps me
organize my thoughts.</p>
<p>This post is for anyone who is still thinking why they should start blogging.</p>
<h3 id="share-your-unique-experience">Share Your Unique Experience</h3>
<p>Even though a particular technology or topic may have been covered extensively
by others, you likely have your own unique experiences and insights to bring to
the conversation. Maybe you&rsquo;ve used a particular technology in a novel way, or
have encountered challenges that others haven&rsquo;t. By sharing your own experience,
you can add a valuable perspective to the conversation and offer new insights to
your readers.</p>
<h3 id="learn-more">Learn More</h3>
<p>Starting a tech blog can also be a great way to learn more about technology. As
you research and write about different topics, you&rsquo;ll inevitably come across new
information and insights that you may not have otherwise discovered. Plus, by
interacting with your readers and other tech enthusiasts online, you can learn
even more about the latest trends and developments.</p>
<h3 id="provide-a-different-format">Provide a Different Format</h3>
<p>While there may be many articles, books, or video tutorials on a particular
technology or topic, not everyone may want to consume information in those
formats. Writing a blog post can provide a quick and easy-to-digest summary or
guide to a particular technology. Additionally, you can provide your own unique
voice and style to make the information more accessible to your readers.</p>
<h3 id="reach-a-different-audience">Reach a Different Audience</h3>
<p>While established tech bloggers may have a loyal following of readers, there are
likely still many people who are interested in the topic but haven&rsquo;t yet found a
resource that speaks to them. By writing a blog post on the topic, you can reach
a new and different audience who may not have been exposed to the information
before.</p>
<h3 id="update-information">Update Information</h3>
<p>Technology is constantly changing and evolving. Even if a topic has been covered
extensively in the past, there may be new updates, features, or security
vulnerabilities that need to be addressed. By writing about these updates, you
can provide valuable and up-to-date information to your readers.</p>
<h3 id="connect-with-like-minded-people">Connect with Like-Minded People</h3>
<p>Starting a blog can also help you connect with like-minded people from all over
the world. By sharing your thoughts and insights online, you can engage with
other tech enthusiasts and build a community of people who share your passion
for technology. This can lead to new friendships, collaborations, and even
business opportunities.</p>
<h3 id="establish-yourself-as-an-expert">Establish Yourself as an Expert</h3>
<p>Writing about a particular technology or topic consistently can help you
establish yourself as an expert in that field. This can be valuable for your
career, as it can help to establish you as a thought leader in your industry or
area of expertise. Additionally, by building a following of readers who are
interested in your content, you may be able to leverage this following for other
opportunities, such as speaking engagements, consulting work, or job offers.</p>
<h3 id="have-fun">Have Fun!</h3>
<p>Finally, starting a blog should be fun! It&rsquo;s a great way to share your
interests and connect with others who share your passions. Plus, there&rsquo;s
something uniquely satisfying about creating content and putting it out into the
world for others to enjoy.</p>
<p>While my blog is mostly tech, the benefits of blogging apply to any niche or
topic. Blogging is a versatile medium that can be used to share your knowledge,
connect with like-minded individuals, and build your personal brand, regardless
of the subject matter.</p>
<p>I encourage you to be the new blogger to explore different topics and niches
that interest you. Whether it&rsquo;s fashion, cooking, travel, or personal
development, there&rsquo;s an audience out there for every type of content. By
starting a blog and sharing your unique perspectives and experiences, you can
create valuable content that resonates with your audience.</p>
</content:encoded>
</item>
<item>
<title>Technical Debt</title>
<link>https://www.vijayanant.com/posts/technical-debt/</link>
<pubDate>Wed, 28 Dec 2022 00:00:00 +0000</pubDate>
<guid>https://www.vijayanant.com/posts/technical-debt/</guid>
<description>Ward Cunningham, co-author of the Agile Manifesto and a pioneer in design patterns and XP, came up with this metaphor as a way of explaining (to non-technical stakeholders) why refactoring was an essential part of software development. He conveys to them that refactoring is as important as shipping software early to maintain their place in the market. He used the debt metaphor as a way of making an analogy to how venture capital is used to get a business off the ground.</description>
<content:encoded><p><a href="https://en.wikipedia.org/wiki/Ward_Cunningham">Ward Cunningham</a>, co-author of
the Agile Manifesto and a pioneer in design patterns and XP, came up with this
metaphor as a way of explaining (to non-technical stakeholders) why refactoring
was an essential part of software development. He conveys to them that
refactoring is as important as shipping software early to maintain their place
in the market. He used the <strong>debt metaphor as a way of making an analogy to how
venture capital is used to get a business off the ground.</strong></p>
<blockquote>
<p>With borrowed money you can do something sooner than you might otherwise, but
then until you pay back that money you&rsquo;ll be paying interest. I thought
borrowing money was a good idea, I thought that rushing software out the door
to get some experience with it was a good idea, but that of course, you would
eventually go back and as you learned things about that software you would
repay that loan by refactoring the program to reflect your experience as you
acquired it.</p>
<p>&ndash; Ward Cunningham</p>
</blockquote>
<h2 id="it-is-not-a-bad-thing">It Is Not A Bad Thing</h2>
<p>The idea that technical debt is inherently a bad thing is a corruption of
Cunningham&rsquo;s original concept. He makes it clear when he says <em>&ldquo;I thought
borrowing money was a good idea&rdquo;.</em> He sees it as the trade-offs made between
rushing to capture the market vs the long-term viability of code.</p>
<p><em>&ldquo;Rushing software out the door to get experience with it is a good idea, but
you need to refactor the code to reflect your experience as understanding
increases.&quot;</em></p>
<p>We have moved quickly to capture the market by taking on some debt. This is
surely a competitive advantage but it comes with a cost.</p>
<h2 id="bad-code-is-not-encouraged">Bad Code Is NOT Encouraged!</h2>
<p>There is a misunderstanding that it is OK to write bad code in order to push
software faster. The argument is - <em>we are going to come back and fix it later
anyway, so why spend time writing clean code now?</em> This is not correct.
Cunningham talks of <em>experience gained</em> as the software progresses, and we are
expected to <em>refactor</em> our code to reflect that experience gained.</p>
<blockquote>
<p>I&rsquo;m never in favour of writing code poorly, but I am in favour of writing code
to reflect your current understanding of a problem even if that understanding
is partial.</p>
<p>&ndash; Ward Cunningham</p>
</blockquote>
<p>He is asking us to write good-quality code even when we accrue debt. <strong>Bad code
is bad at explaining the intent of the code.</strong> It is not clear what was the
understanding when you wrote it. And when the time comes to refactor, it is that
much harder to change the code as you don&rsquo;t understand why it is the way it is.</p>
<p>The debt is supposed to be easier to pay back. Bad code makes repayment harder.
In fact, the debt metaphor works to our advantage only if we write code that is
clean enough to be understood and refactor easily when our understanding of the
problem improves.</p>
<blockquote>
<p>If you can&rsquo;t refactor your software because it is poorly architected or poorly
written, <strong>you don&rsquo;t have technical debt, you have bad software.</strong></p>
</blockquote>
<p><strong>Then, if bad code is not Tech Debt, what is?</strong></p>
<h2 id="what-is-tech-debt">What is Tech Debt?</h2>
<p>Our understanding of the problem evolves with time, and our code should reflect
our current understanding of the problem. We accrue technical debt as the gap
between our current level of understanding and the level of understanding
reflected by the code grows. When we gain experience and understand more
subtleties and nuances of the problem, we refactor our existing code to match
the latest model. We use that experience to <strong>pay down the principle</strong> that we
borrowed when we released code that we knew was not going to reflect a changing
reality.</p>
<blockquote>
<p>Technical Debt here is the accumulated distance between our understanding of
the problem domain and the understanding that the system reflects.</p>
</blockquote>
<p>If we fail to refactor the code, we are <strong>paying interest on the debt</strong> every
time we interact with the code; combining the two disparate models of
understanding increases cognitive overhead, leads to communications problems,
and the cost of adding features becomes higher and higher. Eventually, we simply
can&rsquo;t.</p>
<h2 id="this-is-unfamiliar">This Is Unfamiliar&hellip;</h2>
<p>If all this sounds unfamiliar, or is different from what you have read before,
it is probably because Technical Debt has become conflated with another concept
-<a href="https://en.wikipedia.org/wiki/Entropy">system entropy</a> (a measure of the
degree of disorder in a system). It&rsquo;s easy to write code quickly and ignore good
practices and factoring. Over time, all of these neglects accumulate and we end
up with code that looks more like a jungle than a clean understandable guide to
the behaviour of a system. Code that is hard to understand is very different
from code that has a different understanding of the problem.</p>
<h2 id="an-example-may-help">An example May Help</h2>
<p>Let us assume I am working on a feature that needs to send SMS. I check with
other teams if we already have a service/system that can send SMS. I am told
that you are working on a Notification System/Service that combines email, SMS,
and/or InApp notifications. It will be ready in 2 months. I am also told that
every system will have to use this notification system going forward.</p>
<p>But, I have to launch my feature in 2 weeks; I will not wait for your system to
be ready. I will use a simple SMS library/service to get things rolling.</p>
<p>I have now taken a debt. Once the Notification system is ready and is the
de-facto thing, the debt becomes obvious. Every time we deal with my service we
have to pay the interest in the form of dealing with that SMS library. Any time
we change the Notification, we have to deal with the SMS library. Our mental
model is that every system uses the same notification system, but our code
doesn&rsquo;t follow that model.</p>
<p>Once I switch to using the notification system, I paid back the premium. No more
debt.</p>
<h2 id="another-example-with-code-please">Another Example, With Code Please?</h2>
<p>OK, let us take another example with code. We have an <code>addEvent</code> method that
adds the scheduling event to a collection.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-java" data-lang="java"><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Scheduler</span> <span style="color:#f92672">{</span>
<span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">addEvent</span><span style="color:#f92672">(</span>SchedulingEvent event<span style="color:#f92672">)</span> <span style="color:#f92672">{</span>
events<span style="color:#f92672">.</span><span style="color:#a6e22e">add</span><span style="color:#f92672">(</span>event<span style="color:#f92672">);</span>
<span style="color:#f92672">}</span>
<span style="color:#f92672">...</span>
<span style="color:#f92672">}</span>
</code></pre></div><p>We are asked to have it do another. Whenever we receive a scheduling event, we
need to save it and send it to a peer system also. How can we make this change?</p>
<p>It&rsquo;s very easy. We just add two lines to the code:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-java" data-lang="java"><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Scheduler</span> <span style="color:#f92672">{</span>
<span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">addEvent</span><span style="color:#f92672">(</span>SchedulingEvent event<span style="color:#f92672">)</span> <span style="color:#f92672">{</span>
events<span style="color:#f92672">.</span><span style="color:#a6e22e">add</span><span style="color:#f92672">(</span>event<span style="color:#f92672">);</span>
peerNotifier<span style="color:#f92672">.</span><span style="color:#a6e22e">notify</span><span style="color:#f92672">(</span>event<span style="color:#f92672">);</span>
store<span style="color:#f92672">.</span><span style="color:#a6e22e">save</span><span style="color:#f92672">(</span>event<span style="color:#f92672">);</span>
<span style="color:#f92672">}</span>
<span style="color:#f92672">...</span>
<span style="color:#f92672">}</span>
</code></pre></div><p>We’re adding more responsibilities to a class that is concerned with a different
thing. Schedulers should be about scheduling, not logging, displaying, saving,
or sending information to peers. This is violating Single Responsibility
Principle. Many incorrectly think this is &lsquo;taking on tech debt&rsquo;, a temporary
fix/solution to get the feature out quickly. But we are simply writing bad/messy
code.</p>
<p>What would it be like if we refactored the original code to make it possible to
add our new feature in a pleasant way?</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-java" data-lang="java"><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Scheduler</span> <span style="color:#f92672">{</span>
<span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">registerEventListener</span><span style="color:#f92672">(</span>SchedulingEventListener listener<span style="color:#f92672">)</span> <span style="color:#f92672">{</span>
listeners<span style="color:#f92672">.</span><span style="color:#a6e22e">add</span><span style="color:#f92672">(</span>listener<span style="color:#f92672">);</span>
<span style="color:#f92672">}</span>
<span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">addEvent</span><span style="color:#f92672">(</span>SchedulingEvent event<span style="color:#f92672">)</span> <span style="color:#f92672">{</span>
events<span style="color:#f92672">.</span><span style="color:#a6e22e">add</span><span style="color:#f92672">(</span>event<span style="color:#f92672">);</span>
<span style="color:#66d9ef">for</span><span style="color:#f92672">(</span>SchedulingEventListener listener <span style="color:#f92672">:</span> listeners<span style="color:#f92672">)</span> <span style="color:#f92672">{</span>
listener<span style="color:#f92672">.</span><span style="color:#a6e22e">eventAdded</span><span style="color:#f92672">(</span>event<span style="color:#f92672">)</span>
<span style="color:#f92672">}</span>
<span style="color:#f92672">}</span>
<span style="color:#f92672">...</span>
<span style="color:#f92672">}</span>
</code></pre></div><p>In this version, We can easily register one listener that logs, another that
displays, and another that notifies peers - and in each of these cases, the code
in Scheduler does not have to change. We had to do a bit of work to refactor the
code to this state, but once we have, adding the feature is trivial, and
non-invasive.</p>
<h2 id="tracking-tech-debt">Tracking Tech Debt</h2>
<p>Now that we have some understanding of tech debt and the need for refactoring,
let us think about tracking our debt.</p>
<p>Over time people have come up with many ways to track tech debt. One is through
<strong>code comments.</strong> You add code comments where appropriate to document technical
debt as it arises. Try to include why you are doing it the way you are doing it
and at least one potential solution. Such comments usually start with <code>FIXME</code>,
<code>TODO</code>, or <code>OPTIMIZE</code> tag. Again, remember, bad code is not tech debt. Don&rsquo;t
fill your code base with FIXMEs and TODOs.</p>
<p>It is hard to pin down all tech debt to a location in the code. It is hard to
track if there&rsquo;s nowhere to document it. A <strong>DEBT.md</strong> file provides that
location. DEBT.md is the canonical source of where and how the application code
can and should be improved. This should not be confused with how the application
can be improved.</p>
<p>Instead of maintaining a separate file for debt, some use an <strong>issue tracker</strong>
(Bugzilla or Jira) with a <code>debt</code> tag.</p>
<p>All of this may sound good in theory but have little practicality. Unless you
have a way of measuring the value/cost associated with it, there is no way you
can prioritise such a list and act upon it. And there is no good way to assign
such a value/cost to tech debt.</p>
<h2 id="when-to-refactor">When To Refactor</h2>
<p>Since we cannot assign a cost, we cannot prioritise debts. Then, how do we
decide when and which of the debts we tackle? The answer is simple - just like
your product backlog, for example, the priority is &lsquo;when you need it&rsquo;.</p>
<p>One way to look at this problem (of picking a debt to work on) is to consider
the existing code when we are thinking of adding a feature and ask ourselves
what the code should look like to make it easier for us to add this feature.
Most of the time this involves some generalization, renaming and/or a clarifying
extraction. We can alter the structure a bit and make it ready for the change.
Sometimes this may involve a bigger change. It all depends on whether the
original design anticipated the current change or not.</p>
<p>Look at the example above, the <code>Scheduler</code> class did not anticipate such a
change. Or perhaps it was overkill at that time to add the observer pattern.
Either way, we changed the code to make it easier to add a new feature. We could
say this refactoring effort is the cost. But we couldn&rsquo;t have known this before
the feature was even thought of.</p>
<p>The message is clear, don&rsquo;t use the debt metaphor to justify writing bad code;
you are simply degrading the internal quality. The argument that &lsquo;new features
are needed urgently, and perhaps it is OK to let the code be messy&rsquo; isn&rsquo;t well
founded. Bad code impacts quickly and slows down the new features that are
needed quickly. We usually end up releasing slower than expected and with messy
code which is harder to refactor taking up even more effort when the time comes.
Taking on debt to speed-up delivery only works if you write code that is clean
enough to be understood and refactored.</p>
<blockquote>
<p>Consequence of Tech Debt is quicker to market now and refactoring effort
later. Consequence of bad code is apparent speed now coupled with legacy code
and code rewrite later.</p>
</blockquote>
<h2 id="finally">Finally&hellip;</h2>
<p>Technical Debt is a metaphor initially used to explain the management need for
code refactoring; it is not a development methodology or a design philosophy; it
neither tell you how to design or write code nor does it tell you when to take
debt. The debt metaphor helps us think about how to deal with design problems
and how to communicate that thinking.</p>
</content:encoded>
</item>
<item>
<title>Struggles Of A Newcomer To FP</title>
<link>https://www.vijayanant.com/posts/struggles-of-a-newcomer-to-fp/</link>
<pubDate>Thu, 09 Jun 2022 00:00:00 +0000</pubDate>
<guid>https://www.vijayanant.com/posts/struggles-of-a-newcomer-to-fp/</guid>
<description>One of the challenges that I faced earlier on with FP is coming up with non-imperative solutions (I still do sometimes). I am sure many have faced similar hardships. We, those who have trained ourselves to think imperatively, jump to imperative solution first, then remember/realise we are lacking the corresponding tools (loops, mutability, etc) in our new favourite language (Haskell for example). Quite often this results in ugly recursive solution that we think is functional.</description>
<content:encoded><p>One of the challenges that I faced earlier on with FP is coming up with
non-imperative solutions (I still do sometimes). I am sure many have faced
similar hardships. We, those who have trained ourselves to think imperatively,
jump to imperative solution first, then remember/realise we are lacking the
corresponding tools (loops, mutability, etc) in our new favourite language
(Haskell for example). Quite often this results in ugly recursive solution that
we think is functional.</p>
<p>Today we repeat that once again. We write a <strong>recursive</strong> algorithm and then
modify it to work with <code>fold</code> (and make it worse!). And then realise we missed
something basic and come up with a neat solution or two.</p>
<h2 id="run-length-encoding">Run Length Encoding</h2>
<p>We choose <a href="https://en.wikipedia.org/wiki/Run-length_encoding">Run-Length
Encoding</a> (RLE) &ndash; a lossless
data compression technique to implement. RLE has been used in encoding analog TV
signals, bitmap images, and in possibly many more places. Simply put, RLE
compresses a stream of data items by encoding it as data item followed by count
of consecutive repetitions of that data. For example, <code>AABBBAAAAC</code> is encoded as
<code>A2B3A4C</code>.</p>
<p>Here are some more examples:</p>
<table>
<thead>
<tr>
<th>Original</th>
<th>Encoded</th>
</tr>
</thead>
<tbody>
<tr>
<td>AAAA</td>
<td>A4</td>
</tr>
<tr>
<td>AABBCC</td>
<td>A2B2C2</td>
</tr>
<tr>
<td>ABBC</td>
<td>AB2C</td>
</tr>
<tr>
<td>AB</td>
<td>AB</td>
</tr>
<tr>
<td>aaaAAAaBBb</td>
<td>a3A3aB2b</td>
</tr>
<tr>
<td>Vijay</td>
<td>Vijay</td>
</tr>
<tr>
<td>RunLengthEncoding</td>
<td>RunLengthEncoding</td>
</tr>
</tbody>
</table>
<h2 id="approach-1---basic-recursion">Approach 1 - Basic Recursion</h2>
<p>A quick look at the example gives us our first approach. We pass through the
sequence of data while keeping a running count of repetitions and when the
repetition breaks we replace the repetition with the encoding, reset the count,
and continue with the sequence. Seems straight forward, right?</p>
<p>The idea is simple, we start from the left, process each element (of the list)
one at a time, and accumulate the result (encoded list) in each step.</p>
<p>Here is a <code>Haskell</code> version.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#a6e22e">rle1</span> <span style="color:#f92672">::</span> <span style="color:#66d9ef">String</span> <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">String</span>
<span style="color:#a6e22e">rle1</span> <span style="color:#66d9ef">[]</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#34;&#34;</span>
<span style="color:#a6e22e">rle1</span> (x<span style="color:#66d9ef">:</span>xs) <span style="color:#f92672">=</span> myenc1 <span style="color:#e6db74">&#34;&#34;</span> x <span style="color:#ae81ff">1</span> xs
<span style="color:#a6e22e">myenc1</span> <span style="color:#f92672">::</span> <span style="color:#66d9ef">String</span> <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">Char</span> <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">Int</span> <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">String</span> <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">String</span>
<span style="color:#a6e22e">myenc1</span> enc x n <span style="color:#66d9ef">[]</span> <span style="color:#f92672">=</span> enc <span style="color:#f92672">++</span> (x<span style="color:#66d9ef">:</span>(check n))
<span style="color:#a6e22e">myenc1</span> enc x n (y<span style="color:#66d9ef">:</span>ys) <span style="color:#f92672">=</span> <span style="color:#66d9ef">case</span> y <span style="color:#f92672">==</span> x <span style="color:#66d9ef">of</span>
<span style="color:#66d9ef">True</span> <span style="color:#f92672">-&gt;</span> myenc1 enc x (n<span style="color:#f92672">+</span><span style="color:#ae81ff">1</span>) ys
<span style="color:#66d9ef">False</span> <span style="color:#f92672">-&gt;</span> myenc1 (enc <span style="color:#f92672">++</span> (x<span style="color:#66d9ef">:</span>(check n))) y <span style="color:#ae81ff">1</span> ys
<span style="color:#a6e22e">check</span> <span style="color:#f92672">::</span> <span style="color:#66d9ef">Int</span> <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">String</span>
<span style="color:#a6e22e">check</span> n <span style="color:#f92672">|</span> n <span style="color:#f92672">&gt;</span> <span style="color:#ae81ff">1</span> <span style="color:#f92672">=</span> show n
<span style="color:#f92672">|</span> otherwise <span style="color:#f92672">=</span> <span style="color:#e6db74">&#34;&#34;</span>
</code></pre></div><p>Yes, we are going to have problem understanding what we did here in few months.
We basically have a function <code>myenc1</code> called recursively with the current state
of the program passed as arguments.</p>
<p>After marvelling (crying?) at the code for a while it hits us. We have turned a
list into another (possibly shorter) list. Isn&rsquo;t this similar to folding
(reducing) a list? Can we simplify this code by using <code>fold</code>? Using higher
order functions like fold is supposed to make our code simple and &lsquo;more
functional,&rsquo; right?</p>
<p>Let us give folds a shot.</p>
<h2 id="approach-2---folds">Approach 2 - Folds</h2>
<p>Folding is very much what we are doing. We start from the left, process each
element one at a time, and accumulate the result. Even though conceptually we
can use <code>foldl'</code> here, we have to make some changes.</p>
<p>Firstly, the recursion is handled by fold itself. So, manual recursion calls are
no longer needed. Secondly, the fold function expects a binary function as
argument.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#a6e22e">foldl&#39;</span> <span style="color:#f92672">::</span> <span style="color:#66d9ef">Foldable</span> t <span style="color:#f92672">=&gt;</span> (b <span style="color:#f92672">-&gt;</span> a <span style="color:#f92672">-&gt;</span> b) <span style="color:#f92672">-&gt;</span> b <span style="color:#f92672">-&gt;</span> t a <span style="color:#f92672">-&gt;</span> b
</code></pre></div><p>Here is what we get &ndash;</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#a6e22e">rle2</span> <span style="color:#f92672">::</span> <span style="color:#66d9ef">String</span> <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">String</span>
<span style="color:#a6e22e">rle2</span> <span style="color:#66d9ef">[]</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#34;&#34;</span>
<span style="color:#a6e22e">rle2</span> (x<span style="color:#66d9ef">:</span>xs) <span style="color:#f92672">=</span> <span style="color:#66d9ef">let</span> (e, c, n) <span style="color:#f92672">=</span> foldl&#39; myenc2 (<span style="color:#e6db74">&#34;&#34;</span>, x, <span style="color:#ae81ff">1</span>) xs
<span style="color:#66d9ef">in</span> e <span style="color:#f92672">++</span> (c<span style="color:#66d9ef">:</span> check n)
<span style="color:#a6e22e">myenc2</span> <span style="color:#f92672">::</span> (<span style="color:#66d9ef">String</span>, <span style="color:#66d9ef">Char</span>, <span style="color:#66d9ef">Int</span>) <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">Char</span> <span style="color:#f92672">-&gt;</span> (<span style="color:#66d9ef">String</span>, <span style="color:#66d9ef">Char</span>, <span style="color:#66d9ef">Int</span>)
<span style="color:#a6e22e">myenc2</span> (enc, current, count) x <span style="color:#f92672">=</span>
<span style="color:#66d9ef">case</span> x <span style="color:#f92672">==</span> current <span style="color:#66d9ef">of</span>
<span style="color:#66d9ef">True</span> <span style="color:#f92672">-&gt;</span> (enc, current, count<span style="color:#f92672">+</span><span style="color:#ae81ff">1</span>)
<span style="color:#66d9ef">False</span><span style="color:#f92672">-&gt;</span> (enc <span style="color:#f92672">++</span> (current<span style="color:#66d9ef">:</span>check count), x, <span style="color:#ae81ff">1</span>)
</code></pre></div><p><strong>Yuck</strong>, this isn&rsquo;t any better at all!!</p>
<h2 id="what-is-wrong">What is wrong?</h2>
<p>At this point we are frustrated enough. This is the point at which we ask
ourself what went wrong? And this is when we have to take a step back and
rethink. Is there a better way? Can we rethink the solution?</p>
<h2 id="a-better-approach">A Better Approach?</h2>
<p>Instead of looking at each letter, we can look at a pattern or sub-sequence as a
whole. That is, <code>AAADDCCCCBB</code> can be seen a sequence of <code>A</code>&rsquo;s,<code>D</code>&rsquo;s,<code>C</code>&rsquo;s, and
<code>B</code>&rsquo;s in that order. If we can split the whole thing into a such a grouping, we
can treat each group separately.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#a6e22e">rle3</span> <span style="color:#f92672">::</span> <span style="color:#66d9ef">String</span> <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">String</span>
<span style="color:#a6e22e">rle3</span> <span style="color:#66d9ef">[]</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">[]</span>
<span style="color:#a6e22e">rle3</span> (x<span style="color:#66d9ef">:</span>xs) <span style="color:#f92672">=</span> x<span style="color:#66d9ef">:</span> showLen first <span style="color:#f92672">++</span> rle3 rest
<span style="color:#66d9ef">where</span> (first, rest) <span style="color:#f92672">=</span> span (<span style="color:#f92672">==</span> x) xs
showLen <span style="color:#66d9ef">[]</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">[]</span>
showLen s <span style="color:#f92672">=</span> show (<span style="color:#ae81ff">1</span><span style="color:#f92672">+</span>length s)
</code></pre></div><p>This is much better compared to the initial solution. We no longer maintain
state between function calls. Let us take it to next level.</p>
<h2 id="aha">Aha!!</h2>
<p>What changed in our 3rd approach? Why is it better than the first two? One thing
for sure is we no longer have messy state management. What else? A major
enhancement is that we no longer deal with individual letters. We look at a
bunch of letter as a whole.</p>
<blockquote>
<p>The beauty of programming is to solve smaller generic problems and combining
them to solve much larger problem.</p>
</blockquote>
<p>We are onto something here! Let us look at the problem from this perspective.
Can we identify a smaller, generic problem that we can solve?</p>
<p>Yes, here is a smaller problem - given a bunch of repeating letters, like
&ldquo;<code>AAAAAAAA</code>&rdquo;, can we encode it as &ldquo;<code>A8</code>&rdquo;? The next problem, then, is given a
random string of letters, can I split it into multiple smaller strings of
repeating letters? The only part left now is how to string together these two
smaller solutions to get RLE.</p>
<p>In summary all we need to do is</p>
<ol>
<li>Split a string like &ldquo;AAABCCDD&rdquo; into &ldquo;AAA&rdquo;, &ldquo;B&rdquo;, &ldquo;CC&rdquo;, and &ldquo;DD&rdquo;</li>
<li>Encode the smaller strings as &ldquo;A3&rdquo;, &ldquo;B&rdquo;, &ldquo;C2&rdquo;, and &ldquo;D2&rdquo;</li>
<li>Combine the result to get &ldquo;A3BC2D2&rdquo;</li>
</ol>
<p>Here is how it will look -</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#a6e22e">encode</span> <span style="color:#f92672">::</span> <span style="color:#66d9ef">String</span> <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">String</span>
<span style="color:#a6e22e">encode</span> <span style="color:#66d9ef">[]</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">[]</span>
<span style="color:#a6e22e">encode</span> [x] <span style="color:#f92672">=</span> [x]
<span style="color:#a6e22e">encode</span> s <span style="color:#f92672">=</span> head s <span style="color:#66d9ef">:</span> (show <span style="color:#f92672">.</span> length) s
<span style="color:#a6e22e">rle</span> <span style="color:#f92672">::</span> <span style="color:#66d9ef">String</span> <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">String</span>
<span style="color:#a6e22e">rle</span> <span style="color:#f92672">=</span> concat <span style="color:#f92672">.</span> map encode <span style="color:#f92672">.</span> group
</code></pre></div><p>The <code>group</code> function from <code>Data.List</code> does the first part, <code>encode</code> does the
second part, <code>concat</code> combines the result. We then compose them together.</p>
<h2 id="so-what-does-it-mean">So, What Does It Mean?</h2>
<p>If we take a look at how our code/solution evolved, we notice a few things - 1)
our code improved drastically once we removed state management, 2) in the final
solution, most of the work is done by standard library functions 3) our code
evolved from describing how to solve the problem to declaring how the problem is
to be solved</p>
<p>Aren&rsquo;t these the first few things we hear about FP? Pure functions, a few but
well known abstractions, and most importantly declarative style of programming
where we write code that describes what will be done, not how it will be done.
As a beginner, sticking to these three guidelines/principles will help a lot. Of
course, there is much more to FP, but no need to hurry, it will come to you
naturally as you write more functional code.</p>
<p>There is another lesson here for us - using a language that promotes functional
style of programming (like Haskell, Scala, Clojure, etc.) does not automatically
guarantee simple and maintainable code. If not careful, even FP cannot save us
from ugly and unmaintainable code.</p>
</content:encoded>
</item>
<item>
<title>Higher Ranked Types</title>
<link>https://www.vijayanant.com/posts/higher-ranked-types/</link>
<pubDate>Thu, 24 Jan 2019 00:00:00 +0000</pubDate>
<guid>https://www.vijayanant.com/posts/higher-ranked-types/</guid>
<description>Let&rsquo;s get started with a monomorphic function -
incr :: Int -&gt; Int incr = (+1) The function incr works on values of type Int and nothing else. We can make our function polymorphic by using type parameters in place of concrete types -
incr&#39; :: Num a =&gt; a -&gt; a incr&#39; = (+1) The modified function incr' can work with any type that has a Num instance. Now let us move on and look at a simple higher order function -</description>
<content:encoded><p>Let&rsquo;s get started with a <em>monomorphic</em> function -</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Haskell" data-lang="Haskell"><span style="color:#a6e22e">incr</span> <span style="color:#f92672">::</span> <span style="color:#66d9ef">Int</span> <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">Int</span>
<span style="color:#a6e22e">incr</span> <span style="color:#f92672">=</span> (<span style="color:#f92672">+</span><span style="color:#ae81ff">1</span>)
</code></pre></div><p>The function <code>incr</code> works on values of type <code>Int</code> and nothing else. We can make
our function <em>polymorphic</em> by using type parameters in place of concrete types -</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Haskell" data-lang="Haskell"><span style="color:#a6e22e">incr&#39;</span> <span style="color:#f92672">::</span> <span style="color:#66d9ef">Num</span> a <span style="color:#f92672">=&gt;</span> a <span style="color:#f92672">-&gt;</span> a
<span style="color:#a6e22e">incr&#39;</span> <span style="color:#f92672">=</span> (<span style="color:#f92672">+</span><span style="color:#ae81ff">1</span>)
</code></pre></div><p>The modified function <code>incr'</code> can work with any type that has a <code>Num</code> instance.
Now let us move on and look at a simple <em>higher order</em> function -</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Haskell" data-lang="Haskell"><span style="color:#a6e22e">foo</span> <span style="color:#f92672">::</span> (a <span style="color:#f92672">-&gt;</span> a) <span style="color:#f92672">-&gt;</span> a <span style="color:#f92672">-&gt;</span> a
<span style="color:#a6e22e">foo</span> g x <span style="color:#f92672">=</span> g x
<span style="color:#a6e22e">intval</span> <span style="color:#f92672">=</span> foo (<span style="color:#f92672">+</span><span style="color:#ae81ff">1</span>) <span style="color:#ae81ff">1</span> <span style="color:#75715e">-- 2</span>
<span style="color:#a6e22e">listval</span> <span style="color:#f92672">=</span> foo (<span style="color:#f92672">++</span>[<span style="color:#ae81ff">1</span>]) [<span style="color:#ae81ff">1</span>] <span style="color:#75715e">-- [1, 1]</span>
</code></pre></div><p>The first argument to <code>foo</code> is a function of type <code>a -&gt; a</code> bound to <code>g</code>. Is the
function <code>g</code> polymorphic here? The answer is <strong>No!</strong> The <code>a</code> type is being used
polymorphically here, however, <code>a</code> is bound to whatever is the type of <code>x</code> when
<code>g</code> is applied to <code>x</code> i.e., <code>g</code> is monomorphic!</p>
<p>You don&rsquo;t believe me? Try this</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Haskell" data-lang="Haskell"><span style="color:#a6e22e">badfoo</span> <span style="color:#f92672">::</span> <span style="color:#66d9ef">Show</span> a <span style="color:#f92672">=&gt;</span> (a <span style="color:#f92672">-&gt;</span> a) <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">String</span>
<span style="color:#a6e22e">badfoo</span> g <span style="color:#f92672">=</span> (show (g <span style="color:#ae81ff">1000</span>)) <span style="color:#f92672">++</span> (g <span style="color:#e6db74">&#34;? what!&#34;</span>)
</code></pre></div><p>Or this function -</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Haskell" data-lang="Haskell"><span style="color:#a6e22e">badbar</span> <span style="color:#f92672">::</span> <span style="color:#66d9ef">Show</span> a <span style="color:#f92672">=&gt;</span> (a <span style="color:#f92672">-&gt;</span> a) <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">IO</span> ()
<span style="color:#a6e22e">badbar</span> g <span style="color:#f92672">=</span> <span style="color:#66d9ef">do</span>
print <span style="color:#f92672">$</span> g <span style="color:#ae81ff">100</span>
print <span style="color:#f92672">$</span> g <span style="color:#e6db74">&#34;why?&#34;</span>
</code></pre></div><p>The compiler will not be happy with this code. If <code>g</code> were polymorphic, we
could apply it to both numeric and string values!</p>
<h2 id="polymorphic-functions">Polymorphic Functions</h2>
<p>We make our functions polymorphic by using type parameters instead of fixing the
types. When the function is s applied to a value, the type parameter(s) are
bound to actual type(s). We say the function is <em>instantiated</em> with the given
types. The actual types (of type variables) are set to the types of values
passed to the function.</p>
<p>Actual type of a polymorphic function is decided where the function is used, not
where the function is defined, i.e., the user of the function decides the type.</p>
<p>Same applies to higher order functions. If the types of the argument function are
parameterised, the actual types are decided when the argument function is used.</p>
<p>Coming back to <code>badfoo</code> function, the type of the argument function is <code>(a -&gt; a)</code>. The type for type variable <code>a</code> in <code>(a -&gt; a)</code> is bound when this function
is applied to a value (when we call <code>g 1</code>). This means, for the reminder of this
function body, <code>g</code> is monomorphic.</p>
<p>What we wanted, though, is for <code>g</code> to be polymorphic. We want the type of <code>g</code> to
be bound when user calls <code>badfoo</code> - not when <code>g</code> is used within <code>badfoo</code>.</p>
<h2 id="rank">Rank</h2>
<p>Whenever we want to pass a polymorphic function <code>g</code> as an argument to another
function <code>f</code>, we want the type of <code>g</code> to be decided not within the body of <code>f</code>
but at the caller site - one level up so to say. We say, <code>f</code> is ranked one level
higher than <code>g</code>.</p>
<p>All monomorphic functions are <strong>Rank 0</strong>. All polymorphic functions are Rank 1.
A rank-2 polymorphic function takes as an argument a rank-1 polymorphic
function. A rank-3 functions takes as an argument a rank-2 polymorphic function,
and so on.</p>
<blockquote>
<p>If a higher order function takes as argument a rank (N-1) function,
then it is said to be <strong>Rank-N</strong> polymorphic function.</p>
</blockquote>
<h2 id="rankntypes-ghc-extension">RankNTypes GHC Extension</h2>
<p>Haskell is based on the Hindley-Milner type system - and while it allows us to
write polymorphic functions, it doesn&rsquo;t allow us to write functions which take
polymorphic functions as arguments.</p>
<p>Higher Ranked Types are provided in GHC as a language extension. It can be
enabled via the <code>RankNTypes</code> extension. Practically speaking, enabling
higher-ranked types lets us introduce new variable scopes inside of type
signatures.</p>
<p>Here&rsquo;s the implementation we want:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Haskell" data-lang="Haskell"><span style="color:#75715e">{-# LANGUAGE RankNTypes #-}</span>
<span style="color:#a6e22e">goodfoo</span> <span style="color:#f92672">::</span> (forall a<span style="color:#f92672">.</span> <span style="color:#66d9ef">Show</span> a <span style="color:#f92672">=&gt;</span> a <span style="color:#f92672">-&gt;</span> a) <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">String</span>
<span style="color:#a6e22e">goodfoo</span> g <span style="color:#f92672">=</span> (show (g <span style="color:#ae81ff">1</span>)) <span style="color:#f92672">++</span> (g <span style="color:#e6db74">&#34;Works!&#34;</span>)
</code></pre></div><p>Higher Ranked Types make polymorphic Haskell functions <em>first class</em>.</p>
</content:encoded>
</item>
<item>
<title>GADTs Talk - Bengaluru Haskell Meetup</title>
<link>https://www.vijayanant.com/posts/gadts-talk-bengaluru-haskell-meetup/</link>
<pubDate>Thu, 29 Nov 2018 00:00:00 +0000</pubDate>
<guid>https://www.vijayanant.com/posts/gadts-talk-bengaluru-haskell-meetup/</guid>
<description>Last week I gave a talk at [The Bangalore Haskell User Group] (https://www.meetup.com/The-Bangalore-Haskell-User-Group/) on using GADTs to bring compile time correctness to Haskell programs. The focus of the talk was more towards advocating using Haskell type system features where possible to simplify code. The aim was to show how error handling code can be avoided/removed and still achieve type-safety.
The presentation used for the talk is available here.
I had written a more detailed writeup on the same topic here.</description>
<content:encoded><p>Last week I gave a talk at [The Bangalore Haskell User Group]
(<a href="https://www.meetup.com/The-Bangalore-Haskell-User-Group/">https://www.meetup.com/The-Bangalore-Haskell-User-Group/</a>) on using GADTs to
bring compile time correctness to Haskell programs. The focus of the talk was
more towards advocating using Haskell type system features where possible to
simplify code. The aim was to show how error handling code can be
avoided/removed and still achieve type-safety.</p>
<p>The presentation used for the talk is available
<a href="https://www.vijayanant.com/presentations/gadt.pdf">here</a>.</p>
<p>I had written a more detailed writeup on the same topic <a href="https://www.vijayanant.com/posts/gadts-to-eliminate-runtime-checks/">here</a>.</p>
</content:encoded>
</item>
<item>
<title>The Expression Problem</title>
<link>https://www.vijayanant.com/posts/the-expression-problem/</link>
<pubDate>Tue, 13 Nov 2018 00:00:00 +0000</pubDate>
<guid>https://www.vijayanant.com/posts/the-expression-problem/</guid>
<description>In the previous post I had put forward (rather hastily, I must add) my thoughts on what does expressiveness mean for programming languages. I had this feeling of forgetting something important but couldn&rsquo;t pinpoint what it was. Today, while sipping a hot cup of coffee, I remembered the expression problem.
The Expression Problem is a well known problem in programming language theory dealing with the expressiveness of a programming language. Here is Philip Wadler&rsquo;s original statement of the problem.</description>
<content:encoded><p>In the <a href="https://www.vijayanant.com/posts/expressiveness/">previous post</a> I had put forward
(rather hastily, I must add) my thoughts on what does expressiveness mean for
programming languages. I had this feeling of forgetting something important but
couldn&rsquo;t pinpoint what it was. Today, while sipping a hot cup of coffee, I
remembered <strong>the expression problem</strong>.</p>
<p>The Expression Problem is a well known problem in programming language theory
dealing with the expressiveness of a programming language. Here is <a href="http://homepages.inf.ed.ac.uk/wadler/papers/expression/expression.txt">Philip
Wadler&rsquo;s original statement</a> of the
problem.</p>
<blockquote>
<p>The Expression Problem is a new name for an old problem. The goal is to define
a datatype by cases, where one can add new cases to the datatype and new
functions over the datatype, without recompiling existing code, and while
retaining static type safety (e.g., no casts).</p>
<p>&ndash; <em>Philip Wadler</em></p>
</blockquote>
<p>He goes on to say &ldquo;<em>Whether a language can solve the Expression Problem is a salient
indicator of its capacity for expression.</em>&rdquo;</p>
<p>In this post, we will see two examples, one in Java and one in Haskell to
understand the problem.</p>
<h2 id="oo-programming">OO Programming</h2>
<p>In Object Oriented Programming, it is easy to add new datatypes by defining new
(sub)classes. Since classes encapsulate the operations on the data type, no existing
code needs to be modified. However, adding new functions (operations) over the
datatype is hard. All the datatypes have to be modified and recompiled.</p>
<p>Below is a java version explaining the problem. If you want to add new operation
on the expressions (say, to type-check), you will have to add the new operation
to each object type (Literal and Add) forcing a recompilation of these classes.</p>
<script type="application/javascript" src="https://gist.github.com/vijayanant/231b2470b98a92d38d54c7b982ab6503.js?file=ExpressonProblem.java"></script>
<p><a href="https://en.wikipedia.org/wiki/Visitor_pattern">Visitor design pattern</a> in OO
programming is a known solution to cases where new operations are added over
existing type (hierarchy). However, by using this pattern we will restrict our
ability to add new types. Adding new (element) class (to the hierarchy) forces
changes to all the visitor classes and needs recompilation.</p>
<!-- raw HTML omitted -->
<!-- raw HTML omitted -->
<h2 id="functional-programming">Functional Programming</h2>
<p>In functional programming, we think of functions that operate on values of
certain types. It is easy to add new functions that operate on a datatype. To
add new case to the datatype, we will have to modify all the functions to cater
for the new case.</p>
<p>Typeclasses in Haskell offer a solution. But a naive use of type classes will
not work either! In the below code, the expression</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Haskell" data-lang="Haskell"><span style="color:#66d9ef">if</span> <span style="color:#66d9ef">True</span> <span style="color:#66d9ef">then</span> <span style="color:#66d9ef">Lit</span> <span style="color:#ae81ff">10</span> <span style="color:#66d9ef">else</span> <span style="color:#66d9ef">Add</span> (<span style="color:#66d9ef">Lit</span> <span style="color:#ae81ff">5</span>) (<span style="color:#66d9ef">Lit</span> <span style="color:#ae81ff">5</span>)
</code></pre></div><p>does not typecheck even thought both <code>Lit</code> and <code>Add</code> are instances of <code>Exp</code>
typeclass.</p>
<script type="application/javascript" src="https://gist.github.com/vijayanant/231b2470b98a92d38d54c7b982ab6503.js?file=ExpressionProblem.hs"></script>
<p>In the <em>functional pearl</em> <a href="http://www.cs.ru.nl/~W.Swierstra/Publications/DataTypesALaCarte.pdf">Data types a la carte</a>, <em>Wouter
Swierstra</em> proposes a solution to the expression problem. Philip Wadler himself
calls this the <a href="http://wadler.blogspot.com/2008/02/data-types-la-carte.html">best solution in Haskell</a>.</p>
</content:encoded>
</item>
<item>
<title>Expressiveness</title>
<link>https://www.vijayanant.com/posts/expressiveness/</link>
<pubDate>Thu, 08 Nov 2018 00:00:00 +0000</pubDate>
<guid>https://www.vijayanant.com/posts/expressiveness/</guid>
<description>Last week, I wrote a post comparing simple programs written in Haskell, Python, and Java to demonstrate the expressiveness of Haskell. It got me thinking whether expressiveness is something we can compare between any two programming languages.
Conciseness One thing that is very visible among the three implementations is the size of the programs. Is that a good measure of expressiveness of a language? I don&rsquo;t think so. If being concise is what makes a language expressive, obfuscated C programs would be everywhere and even encouraged.</description>
<content:encoded><p>Last week, I wrote a post comparing simple programs written in Haskell, Python,
and Java to demonstrate the <a href="https://www.vijayanant.com/posts/expressiveness-of-haskell/">expressiveness of Haskell</a>. It got me thinking
whether expressiveness is something we can compare between any two programming
languages.</p>
<h2 id="conciseness">Conciseness</h2>
<p>One thing that is very visible among the three implementations is the size of
the programs. Is that a good measure of expressiveness of a language? I don&rsquo;t
think so. If being concise is what makes a language expressive, <a href="https://www.ioccc.org">obfuscated C</a> programs would be everywhere and even encouraged.</p>
<p>We also have <a href="https://en.wikipedia.org/wiki/APL_(programming_language)">APL</a>, a
unique mathematically-inclined programming language designed for conciseness. To
anyone unfamiliar with the syntax of the language, APL looks like a series of
nonsensical graphical symbols, letters, and numbers. However, to an APL
programmer, each graphical symbol or set of symbols stands in for a mathematical
function.</p>
<p>Trying to be concise took away expressiveness in the case of C but is the
strength of APL.</p>
<h2 id="type-system">Type System</h2>
<p>Type systems restrict possible valid programs in a language. This, in some
sense, should make the statically checked, strongly typed languages less
expressive than the dynamically checked, weakly typed languages as there are
less valid programs that can be constructed. Some programs are invalid in
strongly typed languages but are valid in weakly typed languages.</p>
<p>But, both <a href="https://en.wikipedia.org/wiki/Haskell_(programming_language)">Haskell</a> and <a href="https://en.wikipedia.org/wiki/Lisp_(programming_language)">Lisp</a> are considered
highly expressive languages. Haskell is strongly typed and statically checked
where as Lisp is weakly typed (compared to Haskell) and dynamically checked
language.</p>
<h2 id="programming-paradigm">Programming Paradigm</h2>
<p>I don&rsquo;t consider <a href="https://www.vijayanant.com/posts/thinking-in-imperative-object-oriented-and-functional-way/">programming paradigm</a> to be a property of a programming language, it is rather something that a
language promotes. This is evident in Python which provides many constructs to
supports procedural, object oriented, and functional style of programming.</p>
<p>However, it is definitely possible that some problems and/or their solutions are
better expressed in one style than in other.</p>
<h2 id="time">Time</h2>
<p>How quickly can you express your ideas in a language can also be a measure of
expressiveness. Dynamically typed languages, like Python, Ruby, etc., are
considered to excel at this. However, proponents of modern statically typed
languages like Haskell claim that its <a href="https://en.wikipedia.org/wiki/Type_inference">type inferencing</a> mechanism nullifies this
advantage by being quick to write programs and providing static type safety.</p>
<h2 id="conclusion">Conclusion</h2>
<p>It might be safe to consider expressiveness of a language to be some combination
of each of the above factors. But that adds more fuel to the confusion. What is
the right balance? How do we compare two languages with different <em>weights</em>
associated with each the above factors?</p>
<p>We can also go by the definition where expressiveness is simple measure of all
the things that can be expressed in that language. Most general purpose
programing languages are <a href="https://en.wikipedia.org/wiki/Turing_completeness">Turing Complete</a>, that is they can express
anything <em>computable</em>.</p>
<p>I think each programming language defines what expressiveness means for that
language.</p>
<p>For Lisp and family, being able to express almost anything with its macro system
is its expressive power. For Haskell and family, it is its type system which
allows expressing abstract concepts clearly with added type safety. For Python and
other dynamic languages, expressiveness is a measure of how quickly you can
express the abstraction.</p>
</content:encoded>
</item>
<item>
<title>Expressiveness of Haskell</title>
<link>https://www.vijayanant.com/posts/expressiveness-of-haskell/</link>
<pubDate>Sun, 04 Nov 2018 00:00:00 +0000</pubDate>
<guid>https://www.vijayanant.com/posts/expressiveness-of-haskell/</guid>
<description>My goto answer when someone asks why I like Haskell so much these days is usually &ldquo;I like the expressiveness and run time guarantees of Haskell&rdquo;. For those who are little more interested, I would usually show the popular quick sort or merge sort implementations. I wanted a slightly more complicated, yet commonly known, example to demonstrate what I claimed. This is an attempt at coming up with such an example.</description>
<content:encoded><p>My goto answer when someone asks why I like <a href="https://www.haskell.org">Haskell</a>
so much these days is usually <em>&ldquo;I like the expressiveness and run time
guarantees of Haskell&rdquo;.</em> For those who are little more interested, I would
usually show the popular quick sort or merge sort implementations. I wanted a
slightly more complicated, yet commonly known, example to demonstrate what I
claimed. This is an attempt at coming up with such an example. And turning it
into a blog post makes it available for me all the time (and for other too!!).</p>
<p>I choose Python and Java as other two languages as they are the ones I am fairly
comfortable with and also because they are representatives of objected oriented
and dynamically typed languages. I do not claim mastery over any of these
languages. If you have any suggestions on making any of the these
implementations more expressive, let me know and I will update the sample
accordingly. Other languages are welcome too!</p>
<blockquote>
<p>Edit: <a href="https://www.vijayanant.com/posts/expressiveness/">Here</a> is my take on what
expressiveness mean</p>
</blockquote>
<p>All three versions do the same thing. Define a simple <code>Tree</code> type. Instead of
constructing the tree one-element-at-a-time, we provide a convenient function
<code>fromList</code> which takes a list and adds its elements to tree. We also provide a
way to turn the <code>Tree</code> back to a list by providing <code>inorder</code> function to
<a href="https://en.wikipedia.org/wiki/Tree_traversal">traverse the tree in-order</a></p>
<p>The tree construction happens like this: we split the list in to three parts -
middle element, left-sublist and right-sublist. Then, we recursively construct
left and right sub-tree with the two split parts of the list. The middle element
is used at the current node. Why we do it this way? If you pass a sorted list,
this will construct a binary search tree. In-order traversal on that tree should
return the original sorted list back!</p>
<h2 id="haskell">Haskell</h2>
<script type="application/javascript" src="https://gist.github.com/vijayanant/d557b72bea0eda2b3490ba8e059fb486.js?file=Tree.hs"></script>
<h2 id="python">Python</h2>
<script type="application/javascript" src="https://gist.github.com/vijayanant/d557b72bea0eda2b3490ba8e059fb486.js?file=Tree.py"></script>
<h2 id="java">Java</h2>
<script type="application/javascript" src="https://gist.github.com/vijayanant/d557b72bea0eda2b3490ba8e059fb486.js?file=Tree.java"></script>
</content:encoded>
</item>
<item>
<title>Dependent Types To Eliminate Runtime Checks</title>
<link>https://www.vijayanant.com/posts/dependent-types-to-eliminate-runtime-checks/</link>
<pubDate>Fri, 26 Oct 2018 00:00:00 +0000</pubDate>
<guid>https://www.vijayanant.com/posts/dependent-types-to-eliminate-runtime-checks/</guid>
<description>One of the main advantages of static type checking is to catch errors before we deploy code to production. Dependent Types allow us to eliminate some checks that are usually done at run time. I take a simple example to show how dependent types can be used in that regard in day-to-day programming.
Give Me The Money! Let us start with an example. We will define a simple type for representing money and a function to add money.</description>
<content:encoded><p>One of the main advantages of <a href="https://en.wikipedia.org/wiki/Type_system#Static_type_checking">static type checking</a> is to catch
errors before we deploy code to production. <a href="https://en.wikipedia.org/wiki/Dependent_type">Dependent Types</a> allow us to eliminate some checks
that are usually done at run time. I take a simple example to show how dependent
types can be used in that regard in day-to-day programming.</p>
<h2 id="give-me-the-money">Give Me The Money!</h2>
<p>Let us start with an example. We will define a simple type for representing
money and a function to add money.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Haskell" data-lang="Haskell"><span style="color:#66d9ef">data</span> <span style="color:#66d9ef">Money</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">Money</span> <span style="color:#66d9ef">Rational</span>
</code></pre></div><p>Now we can add them together as</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Haskell" data-lang="Haskell"><span style="color:#a6e22e">add</span> <span style="color:#f92672">::</span> <span style="color:#66d9ef">Money</span> <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">Money</span> <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">Money</span>
<span style="color:#a6e22e">add</span> (<span style="color:#66d9ef">Money</span> m1) (<span style="color:#66d9ef">Money</span> m2) <span style="color:#f92672">=</span> <span style="color:#66d9ef">Money</span> (m1 <span style="color:#f92672">+</span> m2)
<span style="color:#a6e22e">money1</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">Money</span> (<span style="color:#ae81ff">50</span> <span style="color:#f92672">%</span> <span style="color:#ae81ff">100</span>)
<span style="color:#a6e22e">money2</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">Money</span> (<span style="color:#ae81ff">25</span> <span style="color:#f92672">%</span> <span style="color:#ae81ff">100</span>)
<span style="color:#a6e22e">total</span> <span style="color:#f92672">=</span> add money1 money2
</code></pre></div><h2 id="everything-ok-there">Everything OK There?</h2>
<p>There is something we have missed here. The currency. Money is represented in
some <em>currency</em> (like US Dollar) and we cannot add money in different
currencies. For example, you cannot add 2 US dollars and 2 British Pounds.</p>
<p>Lets include currency information in our <code>Money</code> type. A simple approach is to
keep a string representing the currency (&ldquo;GBP&rdquo;, &ldquo;USD&rdquo;, etc.) along with the
amount.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Haskell" data-lang="Haskell"><span style="color:#66d9ef">data</span> <span style="color:#66d9ef">Money</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">Money</span> <span style="color:#66d9ef">String</span> <span style="color:#66d9ef">Rational</span>
<span style="color:#a6e22e">twoDollars</span> <span style="color:#f92672">::</span> <span style="color:#66d9ef">Money</span>
<span style="color:#a6e22e">twoDollars</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">Money</span> <span style="color:#e6db74">&#34;USD&#34;</span> <span style="color:#ae81ff">2</span>
</code></pre></div><h2 id="houston-weve-got-a-problem">Houston, We&rsquo;ve Got a Problem</h2>
<p>The constraint that only <code>Money</code> values with same <code>currency</code> can be added makes
our <code>add</code> function <a href="https://en.wikipedia.org/wiki/Partial_function">partial</a>.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Haskell" data-lang="Haskell"><span style="color:#a6e22e">add</span><span style="color:#f92672">::</span> <span style="color:#66d9ef">Money</span> <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">Money</span> <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">Money</span>
<span style="color:#a6e22e">add</span> (<span style="color:#66d9ef">Money</span> c1 m1) (<span style="color:#66d9ef">Money</span> c2 m2) <span style="color:#f92672">=</span>
<span style="color:#66d9ef">case</span> c1 <span style="color:#f92672">==</span> c2 <span style="color:#66d9ef">of</span>
<span style="color:#66d9ef">True</span> <span style="color:#f92672">-&gt;</span> <span style="color:#66d9ef">Money</span> c1 (m2 <span style="color:#f92672">+</span> m2)
<span style="color:#75715e">-- False -&gt; ?? -- the function is not defined for this value </span>
</code></pre></div><p>Partial functions are bad. They pass type check and fail at runtime. The