This post originated from an RSS feed registered with Agile Buzz
by Keith Ray.
Original Post: Refactor To Polymorphism
Feed Title: MemoRanda
Feed URL: http://homepage.mac.com/1/homepage404ErrorPage.html
Feed Description: Keith Ray's notes to be remembered on agile software development, project management, oo programming, and other topics.
Way back around June 14, 2005, I criticized Apple's suggested solution to for reading and byte-swapping PPob resources: a single very long function named _FlipPPob with switch statement for all the 'known' types of PowerPlant view/control classes. They have subsequently changed their suggested solution to be very much in line with what I was recommending. It's a little different, because they're taking advantage of the fact that PPob resources are always going to be big-endian.
//my code
LStream & LStream::operator >> (UInt32 & outNum)
{
ReadBlock(& outNum, sizeof(outNum));
if ( mByteSwapping )
{
outNum = ByteSwapUInt32( outNum );
}
return (*this);
}
//apple's recommended code is now something like:
LStream & LStream::operator >> (UInt32 & outNum)
{
UInt32 value;
ReadBlock(& value, sizeof(value));
outBool = CFSwapInt32BigToHost(value);
}
// where CFSwapInt32BigToHost is defined to do something like:
#if defined( HOST_IS_BIG_ENDIAN )
return val;
#else
return ByteSwapUInt32(val);
#endif
Looking back at my previous code, I can see where "if" statements could be converted to polymorphism. Most of the read and write methods of my modified LStream class in my original solution would have had an "if" statement (directly, or indirectly like Apple did). Using the Replace Conditional With Polymorphism refactoring, we would create two stream classes: one that does byte-swapping unconditionally, and one that doesn't. A factory method would choose between them - reducing the if statements from one-per-read/write-method (about 8 methods) to just the one in the factory method.
LStream* LStreamFactory( FileRefence& aFile, bool fileIsBigEndian )
{
if ( fileIsBigEndian == HOST_IS_BIG_ENDIAN )
return new LStream( aFile ); // non-byte-swapping stream.
//else
return new LByteSwappingStream( aFile );
}
// don't take the above too literally. I didn't look up what
// parameters LStream actually needs in its constructor.
LByteSwappingStream & LByteSwappingStream::operator >> (UInt32 & outNum)
{
ReadBlock(& outNum, sizeof(outNum));
outNum = ByteSwapUInt32( outNum );
return (*this);
}
//etc.
Note that the base class of LByteSwappingStream (which could be LStream or some common base class) would need to declare methods like "operator >>" as virtual to enable polymorphism.