Recently I encountered and answered the question How to split a string into chunks based on specific length?. The question title may seem trivial, the cause isn't.
That is because the user copied their code from this answer that currently has a score of 304 (+326/-22) on a question that's got 306,000 views:
static IEnumerable<string> Split(string str, int chunkSize) { return Enumerable.Range(0, str.Length / chunkSize) .Select(i => str.Substring(i * chunkSize, chunkSize)); }
Please note that additional code might be required to gracefully handle edge cases (
null
or empty input string,chunkSize == 0
, input string length not divisible bychunkSize
, etc.). The original question doesn't specify any requirements for these edge cases and in real life the requirements might vary so they are out of scope of this answer.
It's ... less optimal code because apart from the missing parameter checks it silently drops the last chunk if the input string length is not % chunkSize. This is what the asker of first question, which I answered, was surprised by.
This restriction is not mentioned in the question's title, nor in its body, but only mentioned in a comment by the OP. It is also named a "side effect" which "might" require additional code in the answer.
Sure, sure, the onus is on the copier of code to check (preferably with a unit test) that the copied code does what they think it does, but no one knows how many times this code has been copied into production and caused grief (if it's even detected), while the fix is so stupidly trivial (yet it took me a couple of attempts to get right).
Three people including me have tried fixing the answer. The fixes keep the code functioning exactly the way it does for the current use case, but stops silently dropping the last chunk and starts returning it instead.
Yet the poster insists on rolling back edits, and instead added prose explaining how they don't want to fix their answer, as well as repeatedly doing so in comments.
What do we do here?
- Keep broken code at the top, doing nothing? (The second answer at +174/-0 won't rise to the top soon.)
- Fix the answer and lock it?
- Add a banner to the answer that more clearly indicates its brokenness?
- Something else?
Why?
Sidenote: this is one instance that for me proves that voting for quality doesn't work. 300.000 people search "C# chunk string", copy the highly-upvoted answer, it seems to work, 1 in 1000 gives an upvote, and then later on have to encounter the bug (you can't convince me that all upvoters only needed the str.Length % chunkLength == 0
scenario) and then fix it in their code but don't go back to turn their upvote into a downvote. Or they do, but can't, because their vote is locked in.