Skip to main content

TinT: Composition vs Inheritance vs Unit Testing

This episode of Testing in the Trenches describes, with appropriate modifications to protect the parties involved, a unit-testing situation I encountered on a client's project.

One question I was asked in a job interview some number of years ago was: "For code reusability, which is better: Inheritance or Composition?"

As I recall from the interview, I chose one - in my case, Inheritance - and defended my choice: there is conceptual power in defining higher-level, common traits and behaviors higher up the hierarchy, and re-using it in its sub-classes, or overriding and refining it when more specific behavior is required. Or something like that.

It was obvious from my interviewer's reaction that he was not impressed with my answer. And I have occasionally wondered, in hindsight, if I should have not chosen either, but talked about both and shown my grasp of both concepts. That might have been the better interview technique.

After all, a couple years later, with more time on a handful more Object-oriented projects, I had developed a different answer to that question. Now I would say, "it depends on the situation."

If one class is a proper sub-class of another, that is, if it is a more specific kind of the other thing, Inheritance makes sense. Think "Is-A" when describing their relationship. An apple is a kind of Fruit; a RedDelicious is a kind of Apple. The ability to define, at the Fruit level, behavior common to all fruits, is a powerful feature of the Object-Oriented programming paradigm.

On the other hand, when one class is a piece of another class, when one is a component part of the other, then Composition makes sense. Think "Has-A" when describing their relationship. A FruitBasket has a RedDelicious in it. One would not expect RedDelicious behavior to have any inherent relationship to that of the FruitBasket. A good abstraction of the problem domain would relate them through Composition. The code reuse of my interview question would come through the proper encapsulation of data and behavior in the right places of the system.

On the third hand, for the three-handed among us, if the two classes come from different problem domains, even if they share some surface similarities, then Composition again likely makes the most sense. A class defined in solving one problem should most likely not inherit from a class that solves a different problem. So in an Education sub-system, ClassList might be better related to the ArrayList data structure by Composition rather than Inheritance. At the very least, Composition would give ClassList access to the public API of ArrayList, but would allow it to define its own API specific to its problem domain, and for its own clients.


Since that's related to but not actually my main topic, I'll direct you here for further reading, in deeper and  more eloquent detail than I've provided here.

All of this question of Composition vs Inheritance became relevant, and tied into Unit Testing, on a recent project. Here's the real-world scenario, abstracted where necessary to protect those involved.

Over the years, the application in question had developed a large and complex inheritance tree. One sub-system used root class A, which had a few dozen concrete sub-classes, call them B1-B25, and an Abstract subclass BAbstr which in turn had dozens more concrete sub-classes C1-C50 and more abstract sub-classes CAbstr1-5, each with more concrete sub-classes D1-D60.

For various reasons, it was decided that a couple of the new additions scheduled for this sub-system should admit that things had gotten out of hand and, rather than inherit from the root class A, we should publish a new Interface for their client classes, and use root class A internally, through Composition.

The catch was that another sub-system accessed some of the functionality of these classes through Reflection. Accessing the functionality when it was inherited from the root class was well-understood. But switching to Composition meant that this sub-system needed to be changed, too, to get the appropriate instance whether it was in the Inheritance hierarchy or accessed via a Composition relationship.

It was my privilege to code the logic to get an instance regardless of its relationship - inheritance or composition - to the root class. I created a method that the existing code calls right before using Reflection on a given class. This new method takes the Class, creates an instance of it, checks what it is using instanceof, and casts it to either the RootClass or the new interface IRootClass accordingly. If it is an implementation of the new interface, it calls getRootClassInstance() to access the object being used via Composition.

public static RootClass getRootClassInstance(Class<?> cl) throws InstantiationException, IllegalAccessException
{
   RootClass rootClassObj = null;
   Object rootClassObjOrWrapper = cl.newInstance();
   if (rootClassObjOrWrapper instanceof RootClass)
      rootClassObj = (RootClass) rootClassObjOrWrapper;
   else if (rootClassObjOrWrapper instanceof IRootClass)
      rootClassObj = ((IRootClass)rootClassObjOrWrapper).getRootClassInstance();
   else
      throw new InstantiationException("Cannot get a RootClass object from " + cl.getName());
   return rootClassObj;
}

How can we unit-test this new code? While it does some Java Reflection, it is basically a function, one that takes a single input parameter and either returns an object or throws an Exception. No side-effects or dependencies to worry about.

So it should be as simple a matter as creating classes that use RootClass through Inheritance or through Composition, and have our tests run them through the function. But we don't want to use existing classes in our code base, as such tests would potentially be fragile by being disconnected from the arbitrarily-chosen RootClass descendants and IRootClass implementations.

Instead, let's create simple, test-only classes to use in unit-testing this new method. First, a test-class that is a descendant of RootClass:
public class UseRootClassByInheritance extends RootClass { }

Then we can test the Inheritance case with something like:
@Test
public void rootClassFoundThruInheritance() throws Exception
{
   RootClass rootClassObject = null;
   Class<?> cl = Class.forName("UseRootClassByInheritance");
   rootClassObject = MyClassUnderTest.getRootClassInstance(cl);
   assertNotNull("RootClass object not found but it should be my parent class!", rootClassObject);
   assertTrue("RootClass was expected to be a parent class but is not", rootClassObject instanceof RootClass);
}

To test the Composition case, we can create a thin test-implementation of the interface with something like:
public class UseRootClassByComposition implements IRootClass
{
   private RootClass myRootClassObj = new RootClass();

   @Override
   public RootClass getRootClassInstance()
   {
      return myRootClassObj;
   }
}

And a simple unit test might look like this:
@Test
public void setupJobFoundThruComposition() throws Exception
{
   Class<?> cl = Class.forName("UseRootClassByComposition");
   RootClass rootClassObject = MyClassUnderTest.getRootClassInstance(cl);
   assertNotNull("RootClass object not found but it should be a member!", rootClassObject);
}

We have more test writing to do at this point, but we now have a good starting point for covering our new code with automated unit tests.

Comments

Popular posts from this blog

Adding Items to a ListView using Scala, ScalaFX and FXML

I have been playing with writing an application using Scala, with its API defined in ScalaFX, which wraps the powerful JavaFX library. For simple exercises, coding the UI by hand was enough. But for more complex forms, I began using the JavaFX Scene Builder tool.

Fortunately, others have blazed this trail, and there are fairly stable ScalaFX and ScalaFXML libraries available.

Using the Scene Builder tool, I laid out my form and included a ListBox to hold possible gender selections.

The Scene Builder tool generated fxml code such as:
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="208.0" prefWidth="275.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <Label layoutX="14.0" layoutY="30.0" text="Name" />
      <Label layoutX="14.0" layoutY="71…

Trigger Windows Scheduled Task from Remote Computer via Jenkins

One thing I love about working in Information Technology is the opportunity - the NEED - to constantly learn new things. If a week goes by in which I have not looked up something on StackOverflow or other message boards, I start lobbying my team for more challenges.

This week, I learned the power of running "SCHTASKS.exe" from a command-line script for a remote server in a Microsoft Windows environment.

If you don't know Schtasks, you can read up on it here: https://msdn.microsoft.com/en-us/library/windows/desktop/bb736357(v=vs.85).aspx

In a nutshell, it is the command-line interface for the Windows Task Scheduler, and allows you (or a system administrator) to create, change, run, query, terminate, and delete scheduled tasks on a work-station, either the local one or a remote one.

Not all of the features are available in older versions. In my scenario below, this was relevant as the local computer will be a Windows 8 machine, and the remote server is, shall we say, a muc…

Fixing "resource modena.css not found" in SBT

I have a project that is building a system in Scala. Its GUI is being defined using the ScalaFX system, which is a thin layer that delegates to the underlying JavaFX tools, components and features.

The application was running with a fine-looking GUI in early testing, but all the builds were being driven by the IDE. For various reasons, we wanted to migrate the build to the SBT system.

But upon launching with
$ sbt run
we would get entries like this in the console:
[info] Running StartHere
May 21, 2016 8:50:28 PM com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged
WARNING: Resource "com/sun/javafx/scene/control/skin/modena/modena.css" not found.

The application would compile without issue and would run correctly, but looked terrible. For instance there would be no edges visible for buttons or for text box input fields.

Obviously, a dependency was missing from the build.sbt file. It was easy enough to add, with a line like the following:
unmanagedJars in Compile += Attribute…