Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have written an Optional type in groovy roughly based on java8s Optional. I implemented and use a fold method and would like to know if it can be improved. First, here comes the Optional (I will only use its fold method for my question though):

class Optional<T> {
    T value

    private Opional(T value) {
        this.value = value
    }

    final Boolean isPresent() {
        value != null
    }

    final Object map(Closure mapper) {
        mapper(value).with { Object result ->
            if (result != null)
                return new Optional(result)
            else
                return new Optional(null)
        }
    }

    final Object flatMap(Closure mapper) {
        if( ! this.isPresent)
            return Optional.empty()
        else
            return this.map(mapper)
    }

    public Object fold(Closure ifEmpty, Closure f) {
        if(isPresent())
            return ifEmpty.call()
        else
            return f.call(value)

    }

    final static Optional<T> of(T value) {
        if(value == null)
            throw new IllegalArgumentException("Argument for Optional.of() must not be null")

        new Optional<T>(value)
    }

    final static Optional<T> empty() {
        new Optional(null)
    }
}

(I ommitted some methods like orElse and others)

Next, there are maybe two result-variables. They are therefore of type Optional. I want to execute an action if at least one of the result variables is present AND successfull. I do it like that:

if( resultA.fold({false}, {it.isSuccess()}) || resultB.fold({false}, {it.isSuccess()}) ) {
    //execute action
}

Is it a good way to use fold here or should I just stay with:

 (resultA.isPresent() && resultA.isSuccess())

Also, can/could this usage of fold be improved or are there other ways to work it out?

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.