top of page
Search

Subclassing vs. Configuration

  • Writer: Kiranbir Sodhia
    Kiranbir Sodhia
  • Nov 9, 2013
  • 2 min read

One of the common patterns you’ll see in abstracting and encapsulating device drivers is the usage of subclassing and/or configuration files.

Subclassing

Subclassing in device drivers isn’t too different than subclassing anywhere else. Below is a quick example.

class SerialIO
{
    public:
    virtual size_t write_sync( void * buffer, size_t length );
};

class USBSerialIO : public SerialIO
{
    public:
    virtual size_t write_sync( void * buffer, size_t length );
};

This seems simple and fine now. However, a common issue just in any subclassing case is the inheritance chain can get long and crazy.

Configuration Files

Configuration files have a different approach. Usually it’s an XML file or even just a header file where you customize what to execute in code, but the implementation is shared. An example is below.

bool send_zlp( ConfigurationType cfg )
{
    switch ( cfg )
    {
        case CFG_A: return true;
        case CFG_B: return false;
        default: return false;
    }
    return false; // may cause unreachable warning in static analysis
}

size_t write_sync( void * buffer, size_t length );
{
    ...
    size_t written = usb_bulk_write( buffer, length );
    if ( send_zlp( __cfg ) )
    {
        written += usb_bulk_write( zlp_buffer, sizeof( zlp_buffer ) );
    }
    ...
}

The issues are pretty obvious in this case. Your implementation can get crazy. Although the benefit is you only have to look at one file to customize and one file to debug. The debugging may or may not be straightforward depending on how badly (deeply) the conditions are nested.

Summary

Which one is better? Yeah, they both sort of suck. It needs to be looked on an application basis. You’ll typically see a lot of bootloaders, scatter/linker files, and UEFI drivers use configuration files such as device trees. This might be due to a limitation of the C++ RT not being loaded early. Similarly, I’ve seen many high-level drivers use inheritance.

The only suggestion I have is to avoid mixing both together. Although configuration files can make sense in cases like language strings, when you abuse them for timeouts and transfer size while subclassing a driver for the same reason, then you’ll end up requiring developers to constantly look at both to debug your code. Then again, your code has no bugs…

 
 
 

Recent Posts

See All

Comments


bottom of page