From time to time, we come across a problem where we must store an object, but we don't know in advance what kind of object we're going to store. I'm going to give a very simple example.

Requirement: All questions have answers. All answers have at least one part. Some answers have more than one part.

We're going to focus on how to store and retrieve multi-part answers. We want our view or possibly our controller to behave differently depending on whether the answer has one part or many parts.

Conceptually (without object storage) we might write the following:

Data Model:

class Answer
    Wording (string or Array of strings)


if ourAnswer.wording instanceof String:
    foreach (answerPart in ourAnswer.wording)

So I think that would be the simplest possible way you could meet that functionality, but I'm not aware of any database that will let us store our objects like that, except maybe JSON. (No POJOs presumably because of static type checking.)

I'm actually using Node.js and Javascript with a NoSQL database here which is why I can get away in my pseudocode with not caring at compile time about whether my Answer.wording is a string or Array. But this is a very common problem when I've been using Java as well and I've not yet found the most elegant solution. For example, imagine trying to write that out in Java. We'd probably do:

public interface Answer {
    public String getAnswer();
public class SingleAnswer implements Answer {
    private String wording;
    public String getAnswer() {
         return this.wording;
public class MultipartAnswer implements Answer {
    private String[] wording;
    public String getAnswer() {
         return doSomethingWithThisArray(this.wording);

... and of course that raises all kinds of weird issues with separation of concerns -- how do we know our Multipart Answer will do the right thing with its array, for example? What if we need to work with the array directly? And so on.

Well these are all implementational issues which we can fix. I'm really interested in the best practice for a language like Javascript where we can't use a hierarchy of objects and specificly, their storage in something like an NoSQL database or even worse, an actual SQL database. This problem is the kind of thing which pops up all the time for me with the LAMP stack.

There may be a simple solution for this specific example: we could assume ALL answers are multi-part answers, some of which have an answerPart array length of 1. Nice, simple, clear, easy and that is in fact what I ended up doing. But what if it isn't so simple and we really don't know what kind of thing we want to store, only that it is one of a finite set of well-defined things? What if our objects are preferredColour objects of either a centipede's shoes (16) or a car's wheels (4, different functionality from whatever it is the centipede's shoes do)?

Too contrived you say? Here's another real-world example I dealt with a few years ago.

Requirement: Ask the user if they suffer from a heart condition. If they do, they must give details of that condition.

Since I was using the LAMP stack, the easiest way to store that was in a database column named heart_condition_details, which may be null. In checks where has_heart_condition?() mattered we could simply return the whether heart_condition_details was null or not. Unfortunately, the framework I was using (cakephp) wouldn't allow me to extend the data model like that, with a boolean type has_heart_condition predicated upon whether heart_condition_details was empty.

In the end, I used separate columns for varchar heart_condition_details and boolean has_heart_condition. To this day, I think, I still regret it.

  • For the SQL part of the question: stackoverflow.com/questions/1730665/…
    – rwong
    Commented Mar 25, 2015 at 19:51
  • THANKS rwong, the other brilliant example I forgot to mention which has happened to me all the time is where a database entity can be a child of either of two or more parents. E.g. a Report_Card which could be submitted by either a parent or a teacher, etc., where both Parents and Teachers are different entities and the foreign key could refer to either. Thanks for the link, which details what to do in that use case, which is also broadly applicable to many NoSQL situations.
    – DMCoding
    Commented Mar 25, 2015 at 20:06

1 Answer 1


But what if it isn't so simple and we really don't know what kind of thing we want to store, only that it is one of a finite set of well-defined things?

This is precisely what a tagged union is for. You can emulate them in Java using an abstract base class with a private constructor, and final inner subclasses. The inner subclasses can use the private constructor, but non-inner classes can't, so you end up with a finite number of subclasses (which can't be extended further because they're final).

public abstract class Answer {
    private Answer() { /* Prevent outside inheritance */ }

    public static final class SingleAnswer extends Answer {
        public final String answer;
        public SingleAnswer(String answer) { this.answer = answer; }

    public static final class MultiPartAnswer extends Answer {
        public final String[] parts;
        public MultiPartAnswer(String[] parts) { this.parts = parts; }

(And of course you can add getters and properly format the braces.)

You can then branch on the kind of Answer in a type safe/foolproof way using the Visitor pattern, or if you have access to Java 8 you could accept two lambdas instead of a visitor, which would be much less boilerplate-heavy than creating anonymous objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.