I likely am asking a very stupid question here, please forgive me.
I am a Java and C# backend-engineer with relatively good knowledge of OOP design patterns. I have recently discovered the debate about OOP vs functional programming and the question i simply can't wrap my head around is this: If there is no state, then how could we update an element based on user input?
Here's a small example showing the problem i am facing (i am aware that JS is not a strictly functional language, but i think it shows my problem relatively well.):
Let's say hat we have a small web page that simply displays a counter and increments its value every time the user clicks a button:
<body>
The count is <span id="data">0</span><br>
<button onClick="inc()">Increment</button>
</body>
Now there's the strictly imperative approach, using a counter variable to store the counter's state:
let data;
window.onload = function(){
data = document.getElementById("data");
}
let counter = 0;
function inc(){
data.innerHTML = ++counter;
}
A more functional approach (at least in my understanding) would be the following code:
let data;
window.onload = function(){
data = document.getElementById("data");
}
function writeValue(val){
data.innerHTML = val;
}
function doIncrement(val){
return val + 1;
}
function readValue(){
return parseInt(data.innerHTML);
}
function inc(){
writeValue(doIncrement(readValue()));
}
The issue i am facing now is that, while the data variable is never altered, data's state still changes over time (every time the counter is updated). I do not really see any real solution to this. Of course, the counter's state needs to be tracked somewhere in order for it to be incremented. We could also call document.getElementById("data")
every time we need to read or write the data, but the problem essentially remains the same. I have to somehow track the page's state in order to process it later.
Edit: Note that i have reassigned (which, i am told, is a bad thing in FP) the value val
to the variable innerHTML
in the writeValue(val)
function. This is the exact line at which i am starting to question my approach.
TL;DR: how would you handle data that is naturally subject to a change in a functional way?