Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reducing duplication in code

Tags:

java

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

like image 315
user3063201 Avatar asked Jun 07 '26 04:06

user3063201


1 Answers

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.

like image 180
Andrei Nicusan Avatar answered Jun 09 '26 01:06

Andrei Nicusan