I’m currently trying to read some binary data using the BinaryReader. I’ve created a helper class to parse this data. Currently it is a static class with this kind of methods:
public static class Parser
{
public static ParseObject1 ReadObject1(BinaryReader reader){...}
public static ParseObject2 ReadObject2(BinaryReader reader{...}
}
Then I use it like this:
...
BinaryReader br = new BinaryReader(@"file.ext");
ParseObject1 po1 = Parser.ReadObject1(br);
...
ParseObject1 po2 = Parser.ReadObject2(br);
...
But then I started thinking, I could also just initialize the class like this
Parser p = new Parser(br);
ParseObject1 po1 = Parser.ReadObject1();
What would be a better implementation.
Which is faster isn’t really relevant here; your concerns are more about concurrency and architecture.
In the case of a static Parser class to which you pass the BinaryReader as an argument to the ReadObject call, you’re providing all of the data to the method, and (presumably, from your example) not persisting any data about the Reader in the Parser; this allows for you to instantiate multiple BinaryReader objects and to invoke the Parser on them separately, with no concurrency or collision problems. (Note that this ONLY applies if you have no persistent static data within your Parser object.)
On the other hand, if your Parser gets passed the BinaryReader object to operate upon, it’s presumably persisting that BinaryReader data within itself; there’s a potential complication there if you have interleaved calls to your Parser with different BinaryReader objects.
If your Parser doesn’t need to maintain state between ReadObject1 and ReadObject2, I’d recommend keeping it static, and passing in the BinaryReader object reference; keeping it static in that instance is a good “descriptor” of the fact that there’s no data persisted between those invocations. On the other hand, if there’s data persisted about the BinaryReader within the Parser, I’d make it non-static, and pass the data in (like in your second example). Making it non-static but with class-persisted data makes it far less likely to cause problems with concurrency.