Home > Software design >  Using a method inside a method
Using a method inside a method

Time:12-13

I've written a bit of code but as you can see most of the code is the same in 3 places, I would like to use the method findSeperator() to then be used in maxInt & minInt. Although I'm not really sure what would be the best way to address that, could you advise?

public void findSeperator(String data) {
    Optional<String> optional = Arrays.stream(data.split(""))
            .filter(e -> !numberPattern.matcher(e).matches())
            .findFirst();
    this.seperator = Arrays.stream(SeperatorEnum.values())
            .filter(e -> e.getSeperator().equals(optional.orElse(null)))
            .findFirst()
            .orElseThrow();
}

public OptionalInt maxInt(String data) {
    findSeperator(data);
    return Arrays.stream(data.split(seperator.getSeperator()))
            .filter(e -> numberPattern.matcher(e).matches())
            .mapToInt(Integer::parseInt)
            .max();
}

public OptionalInt minInt(String data) {
    return Arrays.stream(data.split(seperator.getSeperator()))
            .filter(e -> numberPattern.matcher(e).matches())
            .mapToInt(Integer::parseInt)
            .min();
}

CodePudding user response:

how about you just extract the code into a private method in that class.

like this:

public void findSeperator(String data) {
    Optional<String> optional = basicFilter(data.split("")).findFirst();
    this.seperator = Arrays.stream(SeperatorEnum.values())
            .filter(e -> e.getSeperator().equals(optional.orElse(null)))
            .findFirst()
            .orElseThrow();
}

public OptionalInt maxInt(String data) {
    findSeperator(data);
    return basicFilter(data.split(seperator.getSeperator()))
            .mapToInt(Integer::parseInt)
            .max();
}

public OptionalInt minInt(String data) {
    return basicFilter(data.split(seperator.getSeperator())).mapToInt(Integer::parseInt).min();
}

// method for basic filtering
private String[] basicFilter(String[] toFilter) {
    return Arrays.stream(toFilter).filter(e -> numberPattern.matcher(e).matches());
}

CodePudding user response:

You can wrap your function into a class. Then pass an instance of that class into your maxInt/minInt methods. This is also called the Strategy Pattern. The link to Wikipedia also shows code examples in various programming languages.

Lambda function is another keyword you could look up.

  • Related