File: Marks5.java

package info (click to toggle)
checker-framework-java 3.2.0%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 23,104 kB
  • sloc: java: 145,916; xml: 839; sh: 518; makefile: 404; perl: 26
file content (51 lines) | stat: -rw-r--r-- 2,145 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.math.BigDecimal;
import java.util.Optional;
import java.util.stream.Stream;
import org.checkerframework.checker.optional.qual.Present;

/**
 * Test case for rule #5: "If an Optional chain has a nested Optional chain, or has an intermediate
 * result of Optional, it's probably too complex."
 */
@SuppressWarnings("optional.parameter")
public class Marks5 {

    // Each method adds first and second, treating empty as zero, returning an Optional of the sum,
    // unless BOTH are empty, in which case return an empty Optional.

    Optional<BigDecimal> clever(Optional<BigDecimal> first, Optional<BigDecimal> second) {
        @SuppressWarnings({"methodref.inference.unimplemented", "methodref.receiver.invalid"})
        Optional<BigDecimal> result =
                Stream.of(first, second)
                        .filter(Optional::isPresent)
                        .map(Optional::get)
                        .reduce(BigDecimal::add);
        return result;
    }

    Optional<BigDecimal> clever2(Optional<BigDecimal> first, Optional<BigDecimal> second) {
        Stream<Optional<BigDecimal>> s = Stream.of(first, second);
        @SuppressWarnings("assignment.type.incompatible")
        Stream<@Present Optional<BigDecimal>> filtered =
                s.<Optional<BigDecimal>>filter(Optional::isPresent);
        Stream<BigDecimal> present = filtered.<BigDecimal>map(Optional::get);
        Optional<BigDecimal> result = present.reduce(BigDecimal::add);
        return result;
    }

    Optional<BigDecimal> moreClever(Optional<BigDecimal> first, Optional<BigDecimal> second) {
        Optional<BigDecimal> result =
                first.map(b -> second.map(b::add).orElse(b)).map(Optional::of).orElse(second);
        return result;
    }

    Optional<BigDecimal> clear(Optional<BigDecimal> first, Optional<BigDecimal> second) {
        Optional<BigDecimal> result;
        if (!first.isPresent() && !second.isPresent()) {
            result = Optional.empty();
        } else {
            result = Optional.of(first.orElse(BigDecimal.ZERO).add(second.orElse(BigDecimal.ZERO)));
        }
        return result;
    }
}