4
\$\begingroup\$

My Import method takes some data and writes it to a stream. If the CompressedStore property is true, the contents of that stream should be compressed.

This code works, however I just don't like it. For one, I call serializer.Serialize() twice. I feel this code can be made more concise. Any ideas?

public void Import(IProvisionSource source)
{
   InitializeStore();

   // Call source.Export and populate local data store
   var data = source.Export();
   var serializer = new XmlSerializer(data.GetType());

   var file = CompressedStore ? "KPCData.gz" : "KPCData.xml";
   var path = Path.Combine(DataDirectory, file);
   using (var fileWriter = new FileStream(path, FileMode.Create))
   {
      if (CompressedStore)
      {
         using (var writer = new GZipStream(fileWriter, CompressionLevel.Optimal))
         {
            serializer.Serialize(writer, data);
         }
      }
      else
      {
         serializer.Serialize(fileWriter, data);
      }
   }
}
\$\endgroup\$
4
\$\begingroup\$

By default, GZipStream owns the underlying stream, so it disposes it when it's disposed itself. If you're okay with relying on that, then you could put the right Stream into a variable and then have just one using around it. Something like:

var writer = new FileStream(path, FileMode.Create);

if (CompressedStore)
    writer = new GZipStream(writer, CompressionLevel.Optimal);

using (writer)
{
   serializer.Serialize(writer, data);
}

This avoids the duplication and so it's shorter, but it's also less obviously correct (using combined with new is a good pattern, and it's not used here), so I think your original code is actually the better option. If there was more repetition than just one method call, it could make sense to extract that into a separate method, but that's not the case here.

\$\endgroup\$
  • \$\begingroup\$ Ah! Yea, that was the issue I couldn't get around; I could rewrite it with various conditionals, but every time something wasn't getting disposed. If disposing of GZipStream will also dispose of its FileStream, then I'm probably good. I'll keep this solution in mind! \$\endgroup\$ – Mike Christensen Jan 29 '14 at 1:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.