Naming the patterns we use in code
I’ve been playing around with C#'s Xml libraries today and in particular the XmlWriter class.
I wanted to use it to create an Xml document so I called the XmlWriter.Create() method. One of the overloads for this methods takes in a StringBuilder which I initially thought the XmlWriter used to create the Xml document.
In fact it actually writes the Xml Document into this StringBuilder. This is actually possible to deduct from the documentation provided on the Create method but I only glanced at the type needed initially and misunderstood how it worked.
Now clearly one response to that could be 'well just read the documentation more closely' but wouldn’t it be better if the method was actually XmlWriter.CreateInto(StringBuilder output) for example?
I suppose I could write my own extension method to do this but my initial thought was to name the StringBuilder so that I knew what it was doing:
12~ </td> | var xmlCollectingBuilder = new StringBuilder();var xmlWriter = XmlWriter.Create(xmlCollectingBuilder);~ </td> </tr> </tbody></table> That seems more clear to me and I can see at a glance what the code is doing but something about it feels wrong. I am explicitly referencing the collecting parameter pattern in the code to make it easier for me to understand what’s going on. |
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.