Why do we do code katas? To drill the fundamentals, yes, but also because in the repetition of a simple task we may discover something profound.
Recently someone challenged me to implement JSON.Stringify() from scratch in C#, which led me down some interesting reading that I’d like to share here.
The first test I wrote was to assert that my method stringified primitive types correctly. You know, just to get the obvious stuff out of the way before hitting the really interesting parts of the problem.
I thought I knew most of the primitives but decided to look up the C# reference anyway. Which led me to my first correction… what I really wanted to test was value types, not “primitives”.
Which then led to the surprise… where was String?
Of course, String is not a value type but a reference type. Why was that again? Reading up on StackOverflow provided the answer:
Strings aren’t value types since they can be huge, and need to be stored on the heap. Value types are stored on the stack. Stack allocating strings would break all sorts of things: the stack is only 1MB, you’d have to box each string, incurring a copy penalty, you couldn’t intern strings, and memory usage would balloon, etc…
Got it. I almost clicked away but then noticed this gem of a comment, which led me to read two of Eric Lippert’s posts titled “The Stack is an Implementation Detail.”
In part one, Lippert analyzes the argument and concludes that the stack-vs-heap detail is pretty meaningless when discussing value types and reference types:
Surely the most relevant fact about value types is not the implementation detail of how they are allocated, but rather the by-design semantic meaning of “value type”, namely that they are always copied “by value”. If the relevant thing was their allocation details then we’d have called them “heap types” and “stack types”. But that’s not relevant most of the time.
In part two he provides an excellent summary of memory management on the heap vs the stack. So informative! And all that from just following the questions arising from the first test I wrote!
And that, in a nutshell, is why we do katas.