Skip to content

Observation and Discussion from Review #9

Open

Description

@pmslavin

This issue is to collect observations and comments on the ro-crate-cpp library and to provide a forum for discussing these.

Activity

  1. pmslavin commented on Sep 9, 2026

    @pmslavin
    Author

    CMake FetchContent Module

    CMake contains a FetchContent Module which allows requirements to be automatically retrieved and made available to the build procedure.

    To apply this to Catch2, the CMakeLists.txt should include....

    if(BUILD_TESTING)
        include(FetchContent)

    A definition of the source and version for Catch2 can then be added with FetchContent_Declare()...

        FetchContent_Declare(Catch2 
            GIT_REPOSITORY https://github.com/catchorg/Catch2.git
            GIT_TAG        v3.16.0
        )

    ...and then the package retrieved with FetchContent_MakeAvailable()...

        FetchContent_MakeAvailable(Catch2)

    This has the advantage of not requiring "FindCatch2.cmake" in CMAKE_MODULE_PATH or requiring the user to point to a Catch2Config.cmake file.

  2. pmslavin commented on Sep 9, 2026

    @pmslavin
    Author

    Error strings as static members

    There are a few occasions where the text of error messages is repeated, such as:

    throw std::invalid_argument("Property name cannot be empty.");

    ...and...

    throw std::invalid_argument("Property name cannot be empty.");

    ...and other instances where the same error is repeated for different types (here Property and Value)

    if (property.empty())
    throw std::invalid_argument("Property name cannot be empty.");
    if (value.empty())
    throw std::invalid_argument("Property value cannot be empty.");

    This doesn't represent much of a problem while the library is small, but such messages are likely to proliferate as the library grows and will require being kept in sync when changes are made.

    An alternative is to have a single template form of such strings as a static class member...

    class Entity{
        private:
            static constexpr std::string_view err_propempty{"Property {} cannot be empty"};
    };

    This can then be consumed where required using std::format to customise the message:

    if (property.empty()){
        throw std::invalid_argument(std::format(err_propempty, "name"));
    }

    The same approach can be used for all messages where some component of the text varies, e.g...

    if (entities_.find(id) != entities_.end()) {
    throw std::runtime_error("Entity with id '" + id + "' already exists in the RO-Crate.");
    }

    This requires only a single string to maintain for all errors of a particular type, and having a level of indirection between the exception ctor and the string makes localisation/translation much easier. A more advanced (extreme..?) version of this could have string templates held in a std::map member and then looked up dynamically.

  3. pmslavin commented on Sep 9, 2026

    @pmslavin
    Author

    PropertyValue as a polymorphic type

    In tests such as...

    inline nlohmann::json ROCrate::serializePropertyValue(
    const PropertyValue& value
    ) const {
    if (value.type == ValueType::Reference) {
    return {{"@id", value.value}};
    }
    return value.value;
    }

    ...it is necessary to check if our PropertyValue is the reference or literal type and then return the appropriate form of the value accordingly.

    This can be avoided by having PropertyValue as a base class with LiteralProperty and ReferenceProperty which both provide an overridden value() method which returns a type-specific nlohmann::json representation of their value.

    E.g...

    class PropertyValue{
        public:
            virtual nlohmann::json value() = 0;
    };
    
    class LiteralProperty : public PropertyValue{
        public:
            nlohmann::json value() override{
                return {"Something appropriate for LiteralProperty"};
            }
    };
    
    class ReferenceProperty : public PropertyValue{
        public:
            nlohmann::json value() override{
                return {"Something appropriate for ReferenceProperty"};
            }
    };

    With this hierarchy, the ROCrate::serializePropertyValue method can take a const PropertyValue& pv parameter and simply call the pv.value() method irrespective of the argument's type. E.g...

    nlohmann::json ROCrate::serializePropertyValue(const PropertyValue& pv) const {
        return pv.value()
    }
  4. pmslavin commented on Sep 11, 2026

    @pmslavin
    Author

    std::map things

    [1] std::unordered_map

    Since in ROCrate::addEntity() we have...

    if (entities_.find(id) != entities_.end()) {
    throw std::runtime_error("Entity with id '" + id + "' already exists in the RO-Crate.");
    }

    ...to ensure that entities are unique within the map, there is std::unordered_map which is a genuine hash table with unique keys. Lookups (via .at() or operator[]) for this are constant time (unless there's a collision).

    [2] C++20 std::map.contains()

    As there is target_compile_features(ro-crate-cpp INTERFACE cxx_std_20) in CMakeLists.txt, the .contains() method of std::map is available which is a simpler boolean test of membership for a key which can be used in circumstances like the extract above where we don't need the particular value returned by .find() and are just testing the iterator.

  5. pmslavin commented on Sep 11, 2026

    @pmslavin
    Author

    nlohmann::json things

    [1] Converting to and from json

    At present, an ROCrate constructed in code can be serialized to json, but an ROCrate represented in json cannot be parsed as an object. Also, the serialization function...

    inline void ROCrate::writeOut(const std::string& path) {
    nlohmann::json outCrate = {
    {"@context", "https://w3id.org/ro/crate/1.1/context"},
    {"@graph", nlohmann::json::array()}
    };
    // Iterate over the entities, conver to json and append to the graph
    for (const auto& [id, entity] : entities_) {
    outCrate["@graph"].push_back(serializeEntity(id, entity));
    }
    // Write the JSON representation of the RO-Crate to a file
    std::ofstream outFile(path);
    if (!outFile)
    throw std::runtime_error("Failed to open file for writing: " + path);
    outFile << outCrate.dump(4); // Pretty print with 4 spaces indentation
    }

    ...combines serialization and writing to a file by iterating over all entities.

    The nlohmann::json library has the facility to automatically invoke a serialization/deserialization for a custom type with the to_json/from_json functions. By providing these in a namespace, you can automate conversion between ROCrate and nlohmann::json...

        nlohmann:json j = my_rocrateobj;    // ROCrate -> json
        ROCrate r = j.get<ROCrate>();       // json -> ROCrate

    ...rather than have to directly call a dedicated (de)serialization function every time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions