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

inspect() and inspectErr() can mutate consumed value #2

Open
dcadea opened this issue Nov 16, 2024 · 2 comments
Open

inspect() and inspectErr() can mutate consumed value #2

dcadea opened this issue Nov 16, 2024 · 2 comments
Labels
bug Something isn't working help wanted Extra attention is needed
Milestone

Comments

@dcadea
Copy link
Owner

dcadea commented Nov 16, 2024

Both inspect and inspectErr have a potential side effect of mutating the value wrapped into Result. This is not a desired behavior.

var ok = Result.ok(new Mutable(5))
               .inspect(v -> v.a = 20);

assertThat(ok).hasValue(new Mutable(20)); // !!! should be 'Mutable(5)'

var err = Result.err(new Mutable(2))
                .inspectErr(e -> e.a *= 2);

Assertions.assertThat(errors).containsOnly(new Mutable(4)); // !!! should be 'Mutable(2)'
@dcadea dcadea added bug Something isn't working help wanted Extra attention is needed labels Nov 16, 2024
@dcadea dcadea added this to the 0.2.0 milestone Nov 16, 2024
@nanobreaker
Copy link

Maybe we can try to create a deep copy of the object before passing it to the consumer functions just for for inspect and inspectErr methods, basically this solves the problem.

    default Result<O, E> inspect(Consumer<? super O> op) {
        if (this instanceof Ok(O value)) {
            O copy = deepCopy(value); 
            op.accept(copy);
        }

        return this;
    }

@dcadea
Copy link
Owner Author

dcadea commented Nov 17, 2024

Maybe we can try to create a deep copy of the object before passing it to the consumer functions just for for inspect and inspectErr methods, basically this solves the problem.

    default Result<O, E> inspect(Consumer<? super O> op) {
        if (this instanceof Ok(O value)) {
            O copy = deepCopy(value); 
            op.accept(copy);
        }

        return this;
    }

The value has to be either Serializable or deepCopy(v) should convert the object into a byte array and then construct a new instance out of it. And with byte array you also erase initial type of object and have to do an unsafe cast.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

2 participants