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.
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.