Object Storage where Object Type is variable

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class Answer
Wording (string or Array of strings)
</code>
<code>class Answer Wording (string or Array of strings) </code>
class Answer
    Wording (string or Array of strings)

Controller:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>if ourAnswer.wording instanceof String:
doSomethingWith(ourAnswer)
else
foreach (answerPart in ourAnswer.wording)
doSomethingElseWith(answerPart)
</code>
<code>if ourAnswer.wording instanceof String: doSomethingWith(ourAnswer) else foreach (answerPart in ourAnswer.wording) doSomethingElseWith(answerPart) </code>
if ourAnswer.wording instanceof String:
    doSomethingWith(ourAnswer)
else
    foreach (answerPart in ourAnswer.wording)
        doSomethingElseWith(answerPart)

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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);
}
}
</code>
<code>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); } } </code>
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.

2

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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; }
}
}
</code>
<code>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; } } } </code>
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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật