简体   繁体   中英

How do i avoid using if-else in this code?

As part of my learning process, I am creating a small program in Java that would help a fictitious company help in selling burgers.

In the code below, I created class for a burger and added options to add additions to that burger (like lettuce, carrots etc).

The problem I am facing is how to go about checking each extra addition to the base hamburger (base hamburger meaning only bun and meat) without using if-else too much. One way I tried (you can also see that in code) is by assigning each addition a number, for example, 1 to lettuce, 2 carrots and so on. By adding 1 and 2 we get 3; we can look for 3 to find whether lettuce and carrot are added so that we can calculate price. I did this with other options too.

Some problems arose, however:

  1. There are some cases when a number generated by adding is created twice from different additions this can be tackled somewhat by multiplying the number with some number or by adding 1 as I create more edge cases.

  2. My main problem, by creating such cases, is that it would require a lot of if-else statements, which I am trying to avoid in order to effectively code what i need.

Please suggest if there is any other way to do it. Please note code is not yet complete since I didn't want to create more if-else statements (in hamburger class; method cal_price) to check for additions, but it is enough to fully understand the nature of code. Code is given below:

public class Main {

    public static void main(String[] args) {
    Breadroll breadroll_type = new Breadroll("Sesame Seed Bun");
    meat meat_type = new meat("Beef");
    Hamburger my_burger = new Hamburger("Hamburger",breadroll_type,meat_type);
    my_burger.select_items(1,2,3,4);
    my_burger.cal_price();

    my_burger.getBreadroll_type();
    my_burger.getMeat_type();
    }
}
public class Breadroll {
    private String breadroll_type;

    public Breadroll(String breadroll_type) {
        this.breadroll_type = breadroll_type;
    }

    public String getBreadroll_type() {
        return breadroll_type;
    }
}
public class meat {
    private String meat_type;

    public meat(String meat_type) {
        this.meat_type = meat_type;
    }

    public String getMeat_type() {
        return meat_type;
    }
}

public class Hamburger {

    private String name;
    Breadroll breadroll_type;
    meat meat_type;
    private double base_price; //Price without addons
    private int lettuce;
    private int carrot;
    private int tomato;
    private int cheese;
    private int hot_sauce;
    private  int mustard;
    private int total_select;

    public Hamburger(String name, Breadroll breadroll_type, meat meat_type) {
        this.name = name;
        this.breadroll_type = breadroll_type;
        this.meat_type = meat_type;
        this.base_price = 2.75;
    }


    public void select_items(int lettuce, int carrot, int tomato, int cheese) {

        this.lettuce = lettuce;
        this.carrot = carrot;
        this.tomato = tomato;
        this.cheese = cheese;
        this.total_select = lettuce + carrot + tomato + cheese;


    }


    public void cal_price()
    {
        double final_price;
        double lettuce_price = 0.50;
        double carrots_price = 0.60;
        double tomatos_price = 0.70;
        double cheese_price = 0.85;

        if(total_select == 0) {
            System.out.println("Order Placed : Hamburger with no additions " + getBase_price() + "$");
        }


        else if (total_select == 1) {
            final_price = getBase_price() + lettuce_price;
            System.out.println("Order Placed : Hamburger with all lettuce " + (float) final_price + "$");
        }
        else if (total_select == 2) {
            final_price = getBase_price() + carrots_price;
            System.out.println("Order Placed : Hamburger with all carrot " + (float) final_price + "$");
        }
        else if (total_select == 3) {
            final_price = getBase_price() + tomatos_price;
            System.out.println("Order Placed : Hamburger with all tomato " + (float) final_price + "$");
        }
        else if (total_select == 4) {
            final_price = getBase_price() +cheese_price;
            System.out.println("Order Placed : Hamburger with all cheese " + (float) final_price + "$");
        }
        else if (total_select*100 == 1000) {
            final_price = getBase_price() + lettuce_price + carrots_price + tomatos_price + cheese_price;
            System.out.println("Order Placed : Hamburger with all additions " + (float) final_price + "$");
        }

    }

    public String getName() {
        return name;
    }

    public void getBreadroll_type() {
        System.out.println(breadroll_type.getBreadroll_type());
    }

    public void getMeat_type() {
        System.out.println(meat_type.getMeat_type());
    }

    public double getBase_price() {
        return base_price;
    }

    public int getLettuce() {
        return lettuce;
    }

    public int getCarrot() {
        return carrot;
    }

    public int getTomato() {
        return tomato;
    }

    public int getCheese() {
        return cheese;
    }
}

Your implementation of a 'hamburger' object seems to be a bit over-complicated. Usually object oriented programming to represent actual, physical objects should choose the simplest, most atomic attributes as possible to avoid situations like this. A hamburger either does or does not have lettuce. It either does or does not have tomato. My recommendation is to have separate Boolean variables for each topping, or a Boolean array representing the toppings if you'd prefer. Then, add a get_price() method to your Hamburger which has a single block of if statements for calculating your price. If you really want to get into OOP, each topping could be an object with a price, which you append to a Toppings ArrayList on your hamburger. Then, your get_price() method would use a for-each to total all the prices of your Topping objects, as well as your hamburger's price attribute. This method might be better if you want multiple quantities of the same topping. This is the fun part of programming - you can choose the implementation that makes the most sense to you and try it out!

Made a hamburger with name, breadtype, meattype and added the extra's later on, you can make seperate methods for the breadtype and meat as well. In the extra methods we calculate the extra price beforehand so calling getPrice() sums up all the extras with chosen bread/meat type. There are other ways to do this but this way you'll also have an example of a contract and switch statement. Removed a few ingredients but you get the point.

Also take look at the naming conventions how they are different from yours.

class HamburgerContract {

// Specify your constants in this class so all classes are able to communicate with the same values
// Change the name to something shorter like HBC for easier reference, ie HBC.BR_TYPE_SESAM

public static final int BR_TYPE_SESAM = 1;
public static final int BR_TYPE_HONEY = 2;

public static final int MEAT_TYPE_COW = 1;
public static final int MEAT_TYPE_CHICKEN = 2; 
}

public class Hamburger {

public static void main(String[] args) {

    // Made a hamburger with name, breadtype, meattype and added the extra's later on
    // You can make seperate methods for the breadtype and meat as well
    // In the extra methods we calculate the extra price beforehand
    // So calling getPrice() sums up all the extras with chosen bread/meat type
    // There are other ways to do this but this way you'll also have an example of a contract and switch statement
    // Removed a few ingredients but you get the point

    Hamburger myHamburger = new Hamburger("Varadero Burger", HamburgerContract.BR_TYPE_SESAM, HamburgerContract.MEAT_TYPE_CHICKEN, 2.50);
    myHamburger.addCarrot();
    myHamburger.addLettuce();
    myHamburger.removeCarrot();
    System.out.print("The price of your " + myHamburger.getName() + "is $ " + myHamburger.getPrice());
}

private String burgerName;
private int breadrollType;
private int meatType;

private boolean lettuce;
private boolean carrot;

private double basePrice;
private double extraPrice;

public Hamburger(String burgerName, int breadrollType, int meatType, double basePrice) {

    this.burgerName = burgerName;
    this.breadrollType = breadrollType;
    this.meatType = meatType;
    this.basePrice = basePrice;

    this.extraPrice = 0;

    this.lettuce = false;
    this.carrot = false;
}



public void addLettuce() {
    // extra check if lettuce is not already added, so you wont add to the price twice
    // same goes for removing the lettuce or the carrot methods
    if (!lettuce) {
        letuce = true;
        extraPrice += 0.25;
    }
}

public removeLettuce() {
    if (lettuce) {
        letuce = false;
        extraPrice -= 0.25;
    }
}

public void addCarrot() {
    if (!carrot) {
        carrot = true;
        extraPrice += 0.20;
    }
}

public void removeCarrot() {
    if (carrot) {
        carrot = false;
        extraPrice -= 0.20;
    }
}

public String getName() {
    return burgerName;
}

public double getPrice() {

    switch (breadrollType) {
        case HamburgerContract.BR_TYPE_HONEY: extraPrice += 0.25; break;
        case HamburgerContract.BR_TYPE_SESAM: extraPrice += 0.50; break;
    }

    switch (meatType) {
        case HamburgerContract.MEAT_TYPE_COW: extraPrice += 0; break;
        case HamburgerContract.MEAT_TYPE_CHICKEN: extraPrice += 0.50; break;
    }

    return basePrice + extraPrice;

} 
}

You don't need to use conditional statements at all, just multiply the price of each item by its price:

final_price = getBase_price()
    + lettuce_num * lettuce_price
    + carrots_num * carrots_price
    + tomatos_num * tomatos_price
    + cheese_num * cheese_price;

In your set method you should then set the number/amount of items (eg, lettuce) and not 1 == lettuce and 2 == xxx :

my_burger.select_items(5,0,0,0); // 5 lettuce, 0 all other
my_burger.select_items(1,0,0,90); // 1 lettuce, 90 cheese, 0 all other

Putting it all together (minified):

public class Main {
    public static void main(String[] args) {
        Hamburger my_burger = new Hamburger("Hamburger");
        my_burger.select_items(
            100, // 100 lettuce
            0,   // 0 carrot
            2,   // 2 tomato
            1);  // 1 cheese
        my_burger.cal_price();
    }
}

public class Hamburger {
    private String name;
    private double base_price = 2.75;
    private int lettuce;
    private double lettuce_price = 0.50;
    private int carrot;
    private double carrots_price = 0.60;
    private int tomato;
    private double tomatos_price = 0.70;
    private int cheese;
    private double cheese_price = 0.85;

    public Hamburger(String name) {
        this.name = name;
    }

    public void select_items(int lettuce, int carrot, int tomato, int cheese) {
        this.lettuce = lettuce;
        this.carrot = carrot;
        this.tomato = tomato;
        this.cheese = cheese;
    }

    public void cal_price()
    {
        double final_price = getBase_price()
            + lettuce * lettuce_price
            + carrots * carrots_price
            + tomato * tomatos_price
            + cheese * cheese_price;
        // TODO print price
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM