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.

Popular posts from this blog

Git Reset in Eclipse

Using Git and the Eclipse IDE, you have a series of commits in your branch history, but need to back up to an earlier version. The Git Reset feature is a powerful tool with just a whiff of danger, and is accessible with just a couple clicks in Eclipse. In Eclipse, switch to the History view. In my example it shows a series of 3 changes, 3 separate committed versions of the Person file. After commit 6d5ef3e, the HEAD (shown), Index, and Working Directory all have the same version, Person 3.0.

Scala Collections: A Group of groupBy() Examples

Scala provides a rich Collections API. Let's look at the useful groupBy() function. What does groupBy() do? It takes a collection, assesses each item in that collection against a discriminator function, and returns a Map data structure. Each key in the returned map is a distinct result of the discriminator function, and the key's corresponding value is another collection which contains all elements of the original one that evaluate the same way against the discriminator function. So, for example, here is a collection of Strings: val sports = Seq ("baseball", "ice hockey", "football", "basketball", "110m hurdles", "field hockey") Running it through the Scala interpreter produces this output showing our value's definition: sports: Seq[String] = List(baseball, ice hockey, football, basketball, 110m hurdles, field hockey) We can group those sports names by, say, their first letter. To do so, we need a disc

Java 8: Rewrite For-loops using Stream API

Java 8 Tip: Anytime you write a Java For-loop, ask yourself if you can rewrite it with the Streams API. Now that I have moved to Java 8 in my work and home development, whenever I want to use a For-loop, I write it and then see if I can rewrite it using the Stream API. For example: I have an object called myThing, some Collection-like data structure which contains an arbitrary number of Fields. Something has happened, and I want to set all of the fields to some common state, in my case "Hidden"

How to do Git Rebase in Eclipse

This is an abbreviated version of a fuller post about Git Rebase in Eclipse. See the longer one here : One side-effect of merging Git branches is that it leaves a Merge commit. This can create a history view something like: The clutter of parallel lines shows the life spans of those local branches, and extra commits (nine in the above screen-shot, marked by the green arrows icon). Check out this extreme-case history:  http://agentdero.cachefly.net/unethicalblogger.com/images/branch_madness.jpeg Merge Commits show all the gory details of how the code base evolved. For some teams, that’s what they want or need, all the time. Others may find it unnecessarily long and cluttered. They prefer the history to tell the bigger story, and not dwell on tiny details like every trivial Merge-commit. Git Rebase offers us 2 benefits over Git Merge: First, Rebase allows us to clean up a set of local commits before pushing them to the shared, central repository. For this

Code Coverage in C#.NET Unit Tests - Setting up OpenCover

The purpose of this post is to be a brain-dump for how we set up and used OpenCover and ReportGenerator command-line tools for code coverage analysis and reporting in our projects. The documentation made some assumptions that took some digging to fully understand, so to save my (and maybe others') time and effort in the future, here are my notes. Our project, which I will call CEP for short, includes a handful of sub-projects within the same solution. They are a mix of Web APIs, ASP MVC applications and Class libraries. For Unit Tests, we chose to write them using the MSTest framework, along with the Moq mocking framework. As the various sub-projects evolved, we needed to know more about the coverage of our automated tests. What classes, methods and instructions had tests exercising them, and what ones did not? Code Coverage tools are conveniently built-in for Visual Studio 2017 Enterprise Edition, but not for our Professional Edition installations. Much less for any Commun