Created
May 13, 2018 13:19
-
-
Save softarn/b8b9d8945acf82bb08beff56618d2f85 to your computer and use it in GitHub Desktop.
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
import java.util.Optional; | |
public class OptionalOrElse { | |
public static void main(String[] args) { | |
// Correct usage of orElseGet. createInventoryForUser is not invoked unless. | |
System.out.println("Using the APIs in a correct way"); | |
findInventoryByUserId(1).orElseGet(() -> createInventoryForUser(1)); | |
findInventoryByUserId(2).orElseGet(() -> createInventoryForUser(2)); | |
System.out.println(); | |
// Incorrect usage of orElse. createInventoryForUser is always invoked, even though the user already has an inventory! | |
// This mistake is easy to do because the code reads out so nicely. | |
System.out.println("Using the APIs in an incorrect way"); | |
findInventoryByUserId(1).orElse(createInventoryForUser(1)); | |
findInventoryByUserId(2).orElse(createInventoryForUser(2)); | |
} | |
private static String createInventoryForUser(int userId) { | |
System.out.println("Created inventory for userId: " + userId); | |
return "A new inventory for user: " + userId; | |
} | |
/** | |
* Returns inventory for users. Only user with id 1 has an inventory; | |
*/ | |
private static Optional<String> findInventoryByUserId(int userId) { | |
if (userId == 1) { | |
System.out.println("User with id: " + userId + " has an inventory, returning it"); | |
return Optional.of("An inventory"); | |
} else { | |
System.out.println("Could not find inventory for user with id: " + userId); | |
return Optional.empty(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment