HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Conditionally write to a compressed stream

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
conditionallycompressedstreamwrite

Problem

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);
      }
   }
}

Solution

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.

Code Snippets

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

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

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

Context

StackExchange Code Review Q#40316, answer score: 4

Revisions (0)

No revisions yet.