Framework Design Guidelines: Factored Types


Continuing in our weekly blog post series that highlights a few of the new image[5]_thumb[2]_thumb[2]_thumbadditions to the Framework Design Guidelines 2nd edition.. This content is found in the Factored Types section of Chapter 9: Common Design Patterns. Phil offers some great additions to the base pattern.

PHIL HAACK

Since Factored Types have an explicit lifetime, it probably makes good sense to implement the IDisposable interface so that developers can make use of the using statement. The code sample here could then be refactored to:

using(SerialPort port = new SerialPort("COM1")) {
  
port.Open();
  
GZipStream compressed;
  
compressed = new GZipStream(port.BaseStream,
      CompressionMode.Compress);
   
compressed.Write(data, 0, data.Length);
}

Comments (9)

  1. What's New says:

    Continuing in our weekly blog post series that highlights a few of the new additions to the Framework

  2. Wesley says:

    And a factored type is …?

    Cheers,

    Wes

  3. Ooh says:

    Is there a specific reason why you don’t use the using statement with the GZipStream?

  4. It would be helpful if we knew what "the code sample here" was.  Having the "after" without the "before" is pretty meaningless.

  5. Daniel says:

    I’m not familiar with what a "Factored Type" is either.  A google search did land me on this interesting patent, though:

    http://www.patentstorm.us/patents/7430732/description.html

    Which makes me wonder if I’m legally allowed to use them?

  6. Kevin Daly says:

    First time I’ve heard the term.

    @Daniel : Software patents are evil (and it’s idiotic that they’re granted), but patents on APIs are positively demented.

    Just saying, s’all.

  7. Gavin Greig says:

    From reading the book, but trying to put it into my own words so that I’m not stealing thunder, Factored components are the potentially complex types underlying a simpler facade that is referred to as an Aggregate Component.

    The simple facade may expose the underlying types for developers to implement more complex operations that the facade doesn’t support.

    (I think) Phil Haack’s tip is that all the types involved should implement IDisposable so that it’s easy for developers who use the API to manage the objects’ lifetimes efficiently, through use of the "using" statement.

    Read the book for a definitive explanation.

  8. Bert Huijben says:

    The example code ignores that the gzip stream buffers data to allow its compression.

    For the example to work it should flush (or better yet: close) the GZipStream before closing the serial port.

    (A nested using would probably give the cleanest example)