Last active
July 8, 2020 06:10
-
-
Save filiph/6f56709c39c594413ed6af61d0c4f73c to your computer and use it in GitHub Desktop.
Guard clause
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
/// You can try running this file to see what to expect. | |
/// | |
/// Then, go refactor the function `describeEating()` below. | |
void main() { | |
final filip = Human(); | |
final someoneElse = Human(isFull: true); | |
final shoe = Item(); | |
final banana = Food(isDelicious: true); | |
final kale = Food(); | |
describeEating(shoe, filip); | |
describeEating(banana, filip); | |
describeEating(kale, filip); | |
describeEating(banana, someoneElse); | |
// This is still running Dart without null safety. | |
// Uncomment the line below to get a runtime error. | |
// describeEating(null, filip); | |
} | |
/// This is the function you'll want to refactor. | |
/// | |
/// Hint: I'm not making it too easy for you. | |
/// You'll learn better that way. | |
void describeEating(Item item, Human eater) { | |
if (item != null) { | |
if (!item.isFood) { | |
print("Wait, that's not even food!"); | |
} else { | |
if (!eater.isFull && item.isDelicious) { | |
print("Hmm, that was good."); | |
} else if (eater.isFull) { | |
print("I can't! Too full."); | |
} else { | |
print("Not bad. Nutritious."); | |
} | |
} | |
} else { | |
throw ArgumentError.notNull("item"); | |
} | |
} | |
// ---- Helper classes. No need to touch. | |
class Item { | |
bool get isFood => false; | |
bool get isDelicious => false; | |
} | |
class Food extends Item { | |
bool get isFood => true; | |
bool isDelicious; | |
Food({this.isDelicious = false}); | |
} | |
class Human { | |
bool isFull; | |
Human({this.isFull = false}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment