r/functionalprogramming • u/aviboy2006 • Feb 13 '26
Intro to FP How the functional programming in Scala book simplified my view on side effects
Being a full-stack developer for 15 years, primarily in the imperative/OOP world. I recently started reading Functional Programming in Scala (the "Red Book") to understand the foundational principles behind the paradigm.
I just finished the first chapter, and the example of refactoring a coffee purchase from a side effect to a value was a major turning point for me.
The Initial Impure Code:
( code examples are in Scala )
def buyCoffee(cc: CreditCard): Coffee = {
val cup = new Coffee()
cc.charge(cup.price) // Side effect
cup
}The book highlights that this is difficult to test and impossible to compose. If I want to buy 12 coffees, I hit the payment API 12 times.
The Functional Refactor: By returning a Charge object (a first-class value) alongside the Coffee, the function becomes pure:
def buyCoffee(cc: CreditCard): (Coffee, Charge) = {
val cup = new Coffee()
(cup, Charge(cc, cup.price))
}Why this caught my attention because of :
- Composition: I can now write a coalesce function that takes a List[Charge] and merges them by credit card. We've moved the logic of how to charge outside the what to buy logic.
- Testability: I no longer need mocks or interfaces for the payment processor. I just call the function and check the returned value.
- Referential Transparency: It’s my first real look at the substitution model in action and treating an action as a piece of data I can manipulate before it ever executes.
For those who have been in the FP world for a long time: what were the other foundational examples that helped you bridge the gap from imperative thinking?
6
u/ggbcdvnj Feb 13 '26
Is there a specific name for the pattern you applied here so I can learn more?
7
u/teckhooi Feb 13 '26 edited Feb 13 '26
Coming from OO, the one useful feature I should had learnt long time ago was typeclasses. Java keeps this concept away from me because it is not supported and so are other popular OO languages
5
u/iamevpo Feb 13 '26
Does this ignore the fact there may be not enough balance on the card or it is assumed a credit card, given card , you provide an item for purchase, then a tuple (maybe cup, maybe charge). Looks more realistic rather than always getting a cup
5
u/Solid_Package5977 Feb 13 '26
Yes I am also currently reading this book.. And it is indeed mind opening in some sense..
3
u/Outrageous-Radio5627 Feb 15 '26
It's so amazing, I also started reading this book a couple of days ago and now I see this post with the first example from the book.
1
u/SaladWorking1875 Aug 14 '26
Scale
21
u/[deleted] Feb 13 '26 edited Feb 13 '26
[removed] — view removed comment