Last active
November 8, 2018 12:05
-
-
Save InsulaVentus/c981056a8e7aaf3d59695340aedab02d to your computer and use it in GitHub Desktop.
A functional alternative to an if-else block, using Optional.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main; | |
import java.util.Optional; | |
import static java.lang.String.format; | |
public class ScratchyMcScratch { | |
public static void main(String[] args) { | |
final ScratchyMcScratch mcScratch = new ScratchyMcScratch(); | |
System.out.println(mcScratch.functional("m")); //M: m | |
System.out.println(mcScratch.imperative("m")); //M: m | |
System.out.println(mcScratch.functional("mr")); //MR | |
System.out.println(mcScratch.imperative("mr")); //MR | |
System.out.println(mcScratch.functional("mrmrm")); //mrmrm*** | |
System.out.println(mcScratch.imperative("mrmrm")); //mrmrm*** | |
} | |
/** | |
* Upper cases string if its length is even numbered | |
*/ | |
private static Optional<String> first(final String id) { | |
if (id.length() % 2 == 0) { | |
return Optional.of(id.toUpperCase()); | |
} else { | |
return Optional.empty(); | |
} | |
} | |
/** | |
* Appends '***' to string if its length is greater than 4 | |
*/ | |
private static Optional<String> second(final String id) { | |
if (id.length() > 4) { | |
return Optional.of(id + "***"); | |
} else { | |
return Optional.empty(); | |
} | |
} | |
private String functional(final String id) { | |
return first(id) | |
.map(Optional::of) | |
.orElseGet(() -> second(id)) | |
.orElse(format("M: %s", id)); | |
} | |
private static String first_1(final String id) { | |
return first(id).orElse(null); | |
} | |
private static String second_1(final String id) { | |
return second(id).orElse(null); | |
} | |
private String imperative(final String id) { | |
final String first = first_1(id); | |
if (first != null) { | |
return first; | |
} | |
final String second = second_1(id); | |
if (second != null) { | |
return second; | |
} | |
return format("M: %s", id); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment