Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Draft] Helper methods #126

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft

Conversation

heisluft
Copy link
Contributor

@heisluft heisluft commented Jan 10, 2025

Note: This PR is a draft as I evaluate the best design in terms of user-friendliness, simplicity and performance.

Issue to be solved

In many instances, JsonObjects and arrays are structured in a uniform way, so that we know that a JsonArray contains only JsonObjects, for example.

This however poses a challenge when iterating: The type bound for JsonObject and JsonArray is Object, so every Object has to be iterated and then cast manually, leading to much clutter in client code.

The Solution

Add Helper methods to JsonArray and JsonObject that resembe the forEach() method, but accepting a (Bi-)Consumer of the desired type. Only elements whose type matches the wanted type are handed on to the Consumers in order to prevent ClassCastExceptions.

Alternatives

The alternative I Use uses unchecked casting and then iteration, something akin to

    JsonObject lib; // = ...
    @SuppressWarnings({"unchecked", "rawtypes"})
    List<JsonObject> rules = (List)lib.getArray("rules");
    for(JsonObject rule : rules) doSomething(rule);

but this also erases type safety, potentially leading to unexpected ClassCastExceptions, furthermore we loose all array specific methods if we don't sacrifice an extra line of code for an intermediate variable.

Risks and Assumptions

The main risk lies in the user maybe not expecting not to consume all elements in the case of incompatible objects found. These users, however, can always fall back to the standard List/Map forEach() methods.

@heisluft heisluft changed the title Helper methods [Draft] Helper methods Jan 10, 2025
@heisluft heisluft marked this pull request as draft January 10, 2025 19:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant