Search code examples
c#oopderived-classsubclassing

Is it OK to subclass solely to provide default state/configuration?


Say you have a GUI framework that supports nesting GUI components inside one another. Let's call the base class for any GUI component that can contain other GUI components a Container.

Is it OK to subclass Container soley to provide default configuration, or should subclassing always provide addition/override/implemented behavior? For example, say I wanted to make a ButtonBar container that filled up 100% of the screen width, was 50 pixel in height, and laid out its components horizontally. To configure a Container like that, I could do either of the following two examples:

Container container = new Container();
container.PercentWidth = 100;
container.Height = 50;
container.Layout = Layout.Horizontal;

// use container

OR, (and this is my question), is it OK to do this:

public class ButtonBar : Container
{
    public ButtonBar()
    {
        PercentWidth = 100;
        Height = 50;
        Layout = Layout.Horizontal;
    }
}

ButtonBar buttonBar = new ButtonBar();
// use buttonBar

ButtonBar has no additional functionality over a container, and overrides no Container methods. It just serves to ease configuring a Container to be a ButtonBar.

Edit

I have concluded that it is probably best to use a factory that returns a Container, such as widgetFactory.CreateButtonBar(); This way, you end up using an abstract type (Container), and encapsulate the 'set-up' of the type in a factory, which is what factories do.

public class WidgetFactory
{
    public Container CreateButtonBar()
    {
        Container container = new Container();
        container.PercentWidth = 100;
        container.Height = 50;
        container.Layout = Layout.Horizontal;   

        return container;
    }
}

Solution

  • Your approach is just as correct if some created a subclass just to override a method. One of the main reasons of OOP is for a simple modular design of programs. When you think about it from philosophical stand point your button bar is a different kind of object to a container the difference may seem trivial in a small program but in a larger one it could make the difference of the program being comprehensible.