I currently have multiple code like this for different toppings
// Toppings - Egg
System.out.print("Do you want " + egg.getType() + "?");
input = keyboard.nextLine();
choice = input.charAt(0);
if (choice == 'y') {
l.add(egg.getType());
c.add((double) egg.getCost());
numberOfToppings = numberOfToppings + 1;
totalToppingPrice = totalToppingPrice + egg.getCost();
toppings = toppings + "Egg";
}
It works fine, however i was hoping i could do all toppings in just one block of code. Because i've got around 5 of these, and it takes up far too much, and i've been advised to do so. Anyone got any ideas for how this could be done ? thanks
All the toppings should be gathered together in an enumeration, as long as the topping set is closed and cannot change during the program execution.
enum Topping{
EGG("egg", 22),... ;
private String type;
private double cost;
private Topping(String type, double cost){
this.type = type;
this.cost = cost;
}
//getters and setters
}
Then, you could write a method inside your class containing your code above that should be able to handle a Topping instance, like this:
private handleTopping(Topping top){
System.out.print("Do you want "+top.getType() +"?");
input = keyboard.nextLine();
choice = input.charAt(0);
if (choice == 'y'){
l.add(top.getType());
c.add(top.getCost());
numberOfToppings = numberOfToppings + 1;
totalToppingPrice = totalToppingPrice + top.getCost();
toppings = toppings + " " + top.getType();
}
}
Finally, call the method for all toppings available
for(Topping top : topping.values()){
handleTopping(top);
}
It's all about the DRY (don't repeat yourself principle). It's not even necessarily tied to the object oriented paradigm. Even in procedural programming, one of the core principles is to extract common and frequently used functionalities to parameterized procedures.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With