Skip to content

Instantly share code, notes, and snippets.

@jbrains
Created December 3, 2016 18:05
Show Gist options
  • Save jbrains/ff3065f4abe0d8d0a7effb8f86c1b122 to your computer and use it in GitHub Desktop.
Save jbrains/ff3065f4abe0d8d0a7effb8f86c1b122 to your computer and use it in GitHub Desktop.
PLEASE tell me that there's a better way in Java to write this
// findPrice : String -> Option<Price>
// Option comes from Atlassian's fugue library https://docs.atlassian.com/fugue/4.3.0/fugue/apidocs/index.html
// I want the equivalent of
// case (maybePrice) {
// none => display.displayProductNotFoundMessage(barcode)
// some(price) => display.displayPrice(price)
// }
catalog.findPrice(barcode)
.<Runnable>fold(
() -> (() -> display.displayProductNotFoundMessage(barcode)),
(price) -> (() -> display.displayPrice(price))
).run();
@jbrains
Copy link
Author

jbrains commented Dec 3, 2016

This might be clearer as

            catalog.findPrice(barcode)
                    .<Consumer<Display>> fold(
                            () -> ((display) -> display.displayProductNotFoundMessage(barcode)),
                            (price) -> ((display) -> display.displayPrice(price))
                    ).accept(display);

I'm not entirely sure.

I see that this encourages me to have a generic display function that accepts Either(barcode, price), but I'm not there yet.

@jbrains
Copy link
Author

jbrains commented Dec 3, 2016

I found another alternative.

catalog.findPrice(barcode)
        .toRight(() -> barcode)
        .bimap(
                (barcodeNotFound) -> { display.displayProductNotFoundMessage(barcodeNotFound); return true; },
                (price) -> { display.displayPrice(price); return true; });

Sadly, I'm forced to add return true, because bimap() wants Functions and won't take Consumers.

@gtrefs
Copy link

gtrefs commented Dec 5, 2016

If you are not bound to fugue, you could use Javaslang for this:

Match(catalog.findPrice(barcode)).of(
     Case(Some($()), display::displayPrice), 
     Case(None(), v -> display.displayProdcutNotFoundMessage(barcode))
);

@jbrains
Copy link
Author

jbrains commented Dec 5, 2016

@gtrefs I am absolutely not bound to Fugue and Javaslang looks very interesting. Thank you for introducing me to it!

Pattern matching here looks the same as the plain if statement I had in plain Java, but now I see the equivalent between Option and Either, which I hadn't seen before.

Thanks again!

@jbrains
Copy link
Author

jbrains commented Dec 5, 2016

@gtrefs I had to write this... am I doing it incorrectly? :)

        Match(catalog.findPrice(barcode)).of(
                Case(Some($()), p -> run(() -> display.displayPrice(p))),
                Case(None(), o -> run(() -> display.displayProductNotFoundMessage(barcode)))
        );

@gtrefs
Copy link

gtrefs commented Dec 5, 2016

You are welcome. Glad that I could help :).

The code looks fine to me 👍 The docs say that you should use run if you want to perform side effects with pattern matching (see http://www.javaslang.io/javaslang-docs/#_the_basics_of_match_for_java). In my example, the display functions where not real commands, as they also returned a String. I think Nat Pryce already mentioned, that your code is a mix between imperative and functional. I would rather use Match as an expression and let it return the value which should be displayed (for example, a value type of Message), but I don't know which design you want to achieve. I would do something like this:

@Test
    public void should_find_price(){
        Catalog catalog = new Catalog();
        Barcode barcode = new Barcode();
        Display display = new Display(); // should be mocked
        
        catalog.findPrice(barcode) // maybe a service method catalog.showPriceOn(Barcode barcode, Display display)?
               .map(Message::of)
               .getOrElse(() -> Message.notFound(barcode))
               .showOn(display);
       // assertion is missing 
    }
    
    private String notFoundMessageFor(Barcode barcode) {
        return  barcode.toString();
    }

    public class Catalog {
        public Option<Price> findPrice(Barcode barcode) {
             return Option.none();
        }
    }

    private class Barcode {
        // value type
    }
    
    private static class Message {
        
        private final String message;
        
        private Message(String message){
            this.message = message;
        }

        static Message of(Price price){
            return new Message(price.show());
        }

        static Message notFound(Barcode barcode){
            return new Message(barcode.toString());
        }

        public void showOn(Display display) {
            display.show(message);
        }

        @Override public boolean equals(Object o) {
            if (this == o) { return true; }
            if (o == null || getClass() != o.getClass()) { return false; }
            Message message1 = (Message) o;
            return Objects.equals(message, message1.message);
        }

        @Override public int hashCode() {
            return Objects.hash(message);
        }
        @Override public String toString() {
            return message;
        }
    }

    private static class Display {
        // entity
        public void show(String message){
            System.out.println(message);
        }
    }

    private class Price {
        // value type
        private String show(){
            return toString();
        }   
    }

But that is my inner techie speaking and as I said, I don't know what design you are seeking for.

@jbrains
Copy link
Author

jbrains commented Dec 5, 2016

@gtrefs Thank you. Yes. I have a separate project in which I'm rewriting my entire teaching example with the constraint "no method expectations in the tests", which encourages me to use return values in the way that you describe here (and even pushing Display up the call stack, where it becomes RenderResultView). In that situation, I think of the situation as mapping Option<Price> to Either<String, Price> and then to Either<ProductNotFoundMessage, ProductFoundMessage>. Now the Controller and View negotiate over who dispatches from the message alternatives to send the corresponding message text to the application's output stream.

This is not that project. I'm still using my old, OO approach (fire the right event for each outcome), but I found Fugue (and now Javaslang) intriguing, and so I'm trying to use them together. I can't tell whether the libraries are missing something useful or they're telling me that these types and the fire-event approach are fundamentally incompatible. That's one of the things I'm learning.

@manuelp
Copy link

manuelp commented Dec 5, 2016

My two minutes attempt, using Functional Java. Obviously, untested and from the top of my head!

/* 
 * Assuming:
 *
 * barcode :: Barcode
 * display#displayProductNotFoundMessage() :: F<Barcode, IO<Unit>>
 * display#displayPrice() :: F<Price, IO<Unit>>
*/
catalog.findPrice(barcode) // Option<Price>
    .map(display.displayPrice()) // Option<IO<Unit>>
    .orSome(
	    display.displayProductNotFoundMessage().f(barcode) // IO<Unit>
	    )
    .run();

If the only side effect is printing a String, we could simplify it like this:

/* 
 * Assuming:
 *
 * barcode :: Barcode
 * display#displayProductNotFoundMessage() :: F<Barcode, String>
 * display#displayPrice() :: F<Price, String>
*/
String res = catalog.findPrice(barcode) // Option<Price>
    .map(display.displayPrice()) // Option<String>
    .orSome(
	    display.displayProductNotFoundMessage().f(barcode) // String
	    );
fancyPrint(res);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment