dtonhofer

dtonhofer

Functional Programming in Java, Second Edition: Functional Programming in Java, Second Edition: JUnit code improvements for Chapter 11, pages 189 ff “Refactoring to Rework the Logic”

The usual changes but:

  • The “FirstRepeatedLetter.findIn()” has been improved out of the box. In particular returning ‘\0’ is too C-like and smells like “primitive obsession”. We have null, we should use it. What if the input contains \0 as the matching character?
  • A slightly better code (IMHO) is in FirstRepeatedLetterBetter.findIn()
  • The final refactored code returns not null, but Optional<Character>, which is cleaner.
  • Again, for testing we use a common interface or a wrapper class to avoid having to duplicate testing code.
package chapter11;

import org.junit.jupiter.api.Test;

import java.util.Optional;
import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.*;

public class ReworkTheLogicTest {

    interface FindLetter {

        Character findIn(String word);

    }

    static class FirstRepeatedLetterBefore implements FindLetter {

        public Character findIn(final String word) {
            final char[] letters = word.toCharArray();
            for (char candidate : letters) {
                int count = 0;
                for (char letter : letters) {
                    if (candidate == letter) {
                        count++;
                    }
                }
                if (count > 1) {
                    return candidate;
                }
            }
            return null;
        }
    }

    static class FirstRepeatedLetterBetter implements FindLetter {

        public Character findIn(final String word) {
            char[] letters = word.toCharArray();
            int i = 0;
            Character found = null;
            while (i < letters.length && found == null) {
                // will letter[i] been seen again?
                char maybe = letters[i];
                int j = i + 1;
                while (j < letters.length && letters[j] != maybe) j++;
                if (j < letters.length) {
                    found = maybe;
                } else {
                    i++;
                }
            }
            return found;
        }
    }

    // Does NOT implement "FindLetter", returns Optional<Character>

    static class FirstRepeatedLetterAfter {

        public Optional<Character> findIn(final String word) {
            return Stream.of(word.split(""))
                    .filter(letter -> word.lastIndexOf(letter) > word.indexOf(letter))
                    .findFirst()
                    .map(letter -> letter.charAt(0));
        }
    }

    static class FirstRepeatedLetterAfterWrapped implements FindLetter {

        private final FirstRepeatedLetterAfter finder;

        public FirstRepeatedLetterAfterWrapped(FirstRepeatedLetterAfter finder) {
            this.finder = finder;
        }

        public Character findIn(final String word) {
            return finder.findIn(word).orElse(null);
        }
    }

    private static void commonFindFirstRepeatingTests(final FindLetter finder) {
        assertAll(
                () -> assertEquals('l', finder.findIn("hello")),
                () -> assertEquals('h', finder.findIn("hellothere")),
                () -> assertEquals('a', finder.findIn("magicalguru")),
                () -> assertEquals('z', finder.findIn("abcdefghijklmnopqrstuvwxyzz")),
                () -> assertNull(finder.findIn("once")),
                () -> assertNull(finder.findIn(""))
        );
    }

    @Test
    void findFirstRepeatingBefore() {
        commonFindFirstRepeatingTests(new FirstRepeatedLetterBefore());
    }

    @Test
    void findFirstRepeatingBetter() {
        commonFindFirstRepeatingTests(new FirstRepeatedLetterBetter());
    }

    @Test
    void findFirstRepeatingAfter() {
        commonFindFirstRepeatingTests(new FirstRepeatedLetterAfterWrapped(new FirstRepeatedLetterAfter()));
    }

}

Where Next?

Popular Pragmatic Bookshelf topics Top

abtin
page 20: … protoc command… I had to additionally run the following go get commands in order to be able to compile protobuf code using go...
New
jimschubert
In Chapter 3, the source for index introduces Config on page 31, followed by more code including tests; Config isn’t introduced until pag...
New
Alexandr
Hi everyone! There is an error on the page 71 in the book “Programming machine learning from coding to depp learning” P. Perrotta. You c...
New
mikecargal
Title: Hands-On Rust (Chap 8 (Adding a Heads Up Display) It looks like ​.with_simple_console_no_bg​(SCREEN_WIDTH*2, SCREEN_HEIGHT*2...
New
lirux
Hi Jamis, I think there’s an issue with a test on chapter 6. I own the ebook, version P1.0 Feb. 2019. This test doesn’t pass for me: ...
New
mikecargal
Title: Hands-on Rust: question about get_component (page 295) (feel free to respond. “You dug you’re own hole… good luck”) I have somet...
New
cro
I am working on the “Your Turn” for chapter one and building out the restart button talked about on page 27. It recommends looking into ...
New
gilesdotcodes
In case this helps anyone, I’ve had issues setting up the rails source code. Here were the solutions: In Gemfile, change gem 'rails' t...
New
adamwoolhether
I’m not quite sure what’s going on here, but I’m unable to have to containers successfully complete the Readiness/Liveness checks. I’m im...
New
dtonhofer
@parrt In the context of Chapter 4.3, the grammar Java.g4, meant to parse Java 6 compilation units, no longer passes ANTLR (currently 4....
New

Other popular topics Top

Devtalk
Reading something? Working on something? Planning something? Changing jobs even!? If you’re up for sharing, please let us know what you’...
1033 17470 383
New
AstonJ
What chair do you have while working… and why? Is there a ‘best’ type of chair or working position for developers?
New
AstonJ
SpaceVim seems to be gaining in features and popularity and I just wondered how it compares with SpaceMacs in 2020 - anyone have any thou...
New
brentjanderson
Bought the Moonlander mechanical keyboard. Cherry Brown MX switches. Arms and wrists have been hurting enough that it’s time I did someth...
New
AstonJ
You might be thinking we should just ask who’s not using VSCode :joy: however there are some new additions in the space that might give V...
New
PragmaticBookshelf
Learn different ways of writing concurrent code in Elixir and increase your application's performance, without sacrificing scalability or...
New
DevotionGeo
The V Programming Language Simple language for building maintainable programs V is already mentioned couple of times in the forum, but I...
New
AstonJ
Was just curious to see if any were around, found this one: I got 51/100: Not sure if it was meant to buy I am sure at times the b...
New
PragmaticBookshelf
Programming Ruby is the most complete book on Ruby, covering both the language itself and the standard library as well as commonly used t...
New
PragmaticBookshelf
Fight complexity and reclaim the original spirit of agility by learning to simplify how you develop software. The result: a more humane a...
New

Latest in Functional Programming in Java, Second Edition

Functional Programming in Java, Second Edition Portal

Sub Categories: