java-design-patterns
java-design-patterns copied to clipboard
Code repetition in Flyweight/README.md
https://github.com/iluwatar/java-design-patterns/blob/5b147b00367a500e8dfeac882d4b0d6a0540c6b9/flyweight/README.md?plain=1#L85 The following code is quoted from the documentation of the flyweight design pattern (link above).
if (potion == null) {
switch (type) {
case HEALING -> {
potion = new HealingPotion();
potions.put(type, potion);
}
case HOLY_WATER -> {
potion = new HolyWaterPotion();
potions.put(type, potion);
}
case INVISIBILITY -> {
potion = new InvisibilityPotion();
potions.put(type, potion);
}
default -> {
}
}
}
The following code line is repeating.
potions.put(type, potion);
Suggestion: It can be taken out of the switch-case statement.
LOL nice, i wanna work on this issue
wait i dont think moving that part out will work because, lets say if the input doesnot match the condition it will show default section which is nothing but if you move the "potions.put(type, potion);" out it will execute irrespective of the user input
An exception can be thrown in the default case
Exception for what, Invalid argument?
Well yeah. But we don't need to consider a lot about the Exception since we are talking about design patterns here 😅
Yeah if we create an exception there, it will halt the normal execution and will show the error on console which will ruin the whole code flow ig
This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.
This code snippet demonstrates the creation of a potion using the PotionType class. The PotionType is an enum with four fixed values. By utilizing the new Pattern Matching for Switch. The switch statement will be fully executed without requiring a default case.
Something like that :
if (potion == null) {
potion = switch (type) {
case HEALING -> new HealingPotion();
case INVISIBILITY -> new InvisibilityPotion();
case STRENGTH -> new StrengthPotion();
case HOLY_WATER -> new HolyWaterPotion();
case POISON -> new PoisonPotion();
};
potions.put(type, potion);
}
Please let me know if I’m on the right track or if you have any further suggestions.
is this issue still open?
This issue has been automatically marked as stale because it has not had recent activity. The issue will be unassigned if no further activity occurs. Thank you for your contributions.