I’m writing an app in C# (.net 3.5) and I have a question about class design:
I’d like to create a class which accesses a file (read, write) and provides its content to the users (instanciators) of the class. The most common operation on an instance will be to retrieve a certain value from the file. The actual read and write (io) operations are faily expensive so I’d like to keep the file data in memory and let all instances access this data. The class is located in an assembly that is used from various applications simultaniously, so I guess I should be worrying about thread safety.
How do I design this with respect to thread-safety and unit-testability (for unit-tests, different inputfiles must be used than in operational code)? Any help is greatly appreciated.
Firstly, make your class implement an appropriate interface. That way, clients can test their behaviour without needing real files at all.
Testing the thread safety is hard – I’ve never seen anything which is really useful on that front, though that’s not to say the tools aren’t out there.
For unit testing your class, I’d suggest that if possible it should work with a general stream rather than just a file. Then you can embed different test files in your test assembly, and refer to them with GetManifestResourceStream. I’ve done this several times in the past, with great success.