Enabling forward traversal—Krzysztof Ostrowski

Save to:
Instapaper Pocket Readability

Krzysztof Ostrowski describes in his article enabling iteration over a sequence of objects of given type without changing the type name itself.

Enabling forward traversal

by Krzysztof Ostrowski

From the article:

Let's consider following example. We have legacy interface that constructs object of type T using information stored in object of type U:

bool build_from(T& into, const U& from);

Such a build_from can be deserialiser function, e.g. from JSON to C++ type, for example:

result_type deserialise(T& into, const json_node_type& from);

Ideally, we should return into rather than taking it as an input argument, i.e. return optional<T> or type that carries information about the errors too, like C++ counterpart of Either. Unfortunately, we have to deal with legacy interafce, so that existing contracts cannot be broken, and our patch sets shall favour composition and extension over the modification.

With deserialise we know how to convert internal JSON representation into object of type T. That works fine for non-structured types. JSON offers associative containers (dictionaries, hashes, structures as defined in YAML) and collections. Dictionaries map easily to product types, struct in C++, and for those we typically need custom deserialisation procedures. Collections may be seen as abstractions over structures, or – more functionally – as sequenced values of type T for collection of type [T]. Since we know how to deserialise objects of type T, we can deserialise [T] by simply mapping deserialise over a sequence of T objects, that is doing forward traversal. Unfortunately we have just one JSON node from, not a sequence of nodes. We need to enable forward traversal for the type json_node_type with minimal number of changes.

Add a Comment

You must sign in or register to add a comment.

Comments (0)

There are currently no comments on this entry.