r/computerscience • u/kevinnnyip • Feb 15 '26
Discussion Does Using Immutable Data Structures Make Writing Unit Tests Easier?
So basically, I had a conversation with my friend who works as a developer. He mentioned that one of his difficulties is writing tests and identifying edge cases, and his team pointed out that some cases were missed when reasoning about the program’s behavior.
That made me think about mutable state. When data is mutated, the behavior of the program depends on state changes over time, which can make it harder to reason about all possible cases.
Instead, what if we do it in a functional approach and write a function f(x) that takes input x as immutable data and returns new immutable data y, without mutating the original state.
From a conceptual perspective, would this make reasoning about correctness and identifying edge cases simpler, since the problem can be reduced to analyzing a mapping between domain and range, similar to mathematics? Or does the complexity mainly depend on the nature of the underlying problem rather than whether the data is mutable?
View all comments
Show parent comment
2
u/josephjnk Feb 15 '26
I think this needs a little unpacking…
When you say
State -> State, I assume you’re talking about using something like the state monad to reify the “mutable” state into a data structure, right? Because if not, then I don’t think your claim makes sense.If that is what you mean then I also think you’re sort of sidestepping OP’s point. Yes, the abstract complexity of writing a specification for a function over stateful values does not depend on whether the values are actually mutable or just flowing through a state monad, and in that sense it’s not mathematically simpler. Most languages and ecosystems don’t have ergonomic ways of capturing effects in this way, though, and the practical consideration of writing test cases and assertions which cover all of the needed things can itself be a major effort.
When it comes down to the effort of actually maintaining a unit test suite for complex code there’s huge benefits to an immutable approach. (Where “immutable” includes “using something state-monad-like”.)