Creating a view of data is a concept used extensively by database developers but is rarely used in other software domains. However, the view concept is equally valid in all programming domains where data is central to the nature of the problem being solved.
When data needs to be presented in different ways, the natural solution is to create multiple copies of the data with each copy arranged in a specific manner. This is not always the most efficient solution and can lead to overcomplicated or duplicated code further down the line.
This is the problem that view objects solve; they provide an efficient and concise means of presenting data in multiple ways without inefficiency. Let's consider a simple example. Say that we have a vector of sales records where each sales record is an instance of a record class that we have written.
vector<record> records;
Let's say that in our program we need to be able to present the records in ascending order of sales value. The natural response is to simply sort the vector object. Something similar to the following:
sort( records.begin(), records.end(), someFunctor );
However, this is changing the data. That is, the records in the vector object are being rearranged so that they are in a different order. In this simple case this is fine. But what happens if the program now needs to present the data in ascending order of sales date as well? Now the program needs two presentations of the data; one sorted by sales value and one sorted by sales date.
Without views, there are two solutions to this problem. You could make a copy of the records vector (so that there are two records vectors) and apply a different sorting to each one. Alternatively you could sort the vector just-in-time, that is, apply the sort-by-date algorithm just before you need to access the data by date and then apply the sort-by-value algorithm as and when you need to access it by value.
Both of these solutions have obvious efficiency and scalability issues (see Figure 1). As time goes by and more and more representations of the data are required, so the efficiency further decreases.
The view-based solution to this problem is simple: create one view of the record vector which is sorted by date and another view that is sorted by value. (See Figure 2.)
There is only one copy of the original record vector in memory and it is never changed by the views. As time goes by and new representations of the vector are required, new views are created. This scales better than the previous two solutions because a view needs to be built just once, avoiding repeatedly rearranging the data, and does not create extra copies of data thus reducing memory usage.
In this article I will show how to develop a view class that can be used to implement the view concept in any C++ program.